How to categorize data based on column values in pandas?

南楼画角 提交于 2020-06-13 00:29:46

问题


Let say I have this dataframe:

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 
        'payout': [.1, .15, .2, .3, 1.2, 1.3, 1.45, 2, 2.04, 3.011, 3.45, 1], 
        'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 
        'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
        'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'payout', 'name', 'preTestScore', 'postTestScore'])

Now, I want to build these categories based on the column "payout":

Cat1 : 0 <= x <= 1
Cat2 : 1 <  x <= 2
Cat3 : 2 <  x <= 3
Cat4 : 3 <  x <= 4

and build the sum of the column postTestscore

I do it this way, using the boolean indexing:

df.loc[(df['payout'] > 0) & (df['payout'] <= 1), 'postTestScore'].sum()
df.loc[(df['payout'] > 1) & (df['payout'] <= 2), 'postTestScore'].sum()
etc...

Well it works, but does anyone know a more succinct (pythonic) solution of this one?

来源:https://stackoverflow.com/questions/46138994/how-to-categorize-data-based-on-column-values-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!