Skip to content
Advertisement

How to make column value categories and add to a new column?

I have a dataframe with Heart rate values ranging 0-280 in one column. I am making categories and adding them to a new column as follows:

HR_df1['HRCat']=''
HR_df1.loc[(HR_df1['HR'] > 10) & (HR_df1['HR'] <= 20), 'HRCat'] = '10-20'
HR_df1.loc[(HR_df1['HR'] > 20) & (HR_df1['HR'] <= 30), 'HRCat'] = '20-30'
HR_df1.loc[(HR_df1['HR'] > 30) & (HR_df1['HR'] <= 40), 'HRCat'] = '30-40'
...
HR_df1.loc[(HR_df1['HR'] > 260) & (HR_df1['HR'] <= 270), 'HRCat'] = '260-270'
HR_df1.loc[HR_df1['HR'] > 270,'HRCat'] = '270-280'

This is a hectic task and need more line of code. Is there any way I can do the same using Loops in Python?

Advertisement

Answer

Just use a one-liner:

HR_df1['HRCat'] = pd.cut(df['HR'], np.arange(-1, 281, 10), labels=[f'{x}-{x + 10}' for x in np.arange(0, 280, 10)])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement