Add column for percentage of total to Pandas dataframe

本小妞迷上赌 提交于 2021-01-21 12:33:51

问题


I have a dataframe that I am doing a groupby() on to get the counts on a column's values. I am trying to add an additional column for "Percentage of Total". I'm not sure how to accomplish that.

I've looked at a few groupby options, but can't seem to find anything that fits.

My dataframe looks like this:

              DAYSLATE
DAYSLATE          
-7 days          1
-5 days          2
-3 days          8
-2 days          9
-1 days         45
0 days         589
1 days          33
2 days           8
3 days          16
4 days          14
5 days          16
6 days           2
7 days           6
8 days           2
9 days           2
10 days          1

回答1:


Option 1

df['DAYSLATE_pct'] = df.DAYSLATE / df.DAYSLATE.sum()

Option 2
Use pd.value_counts instead of groupby

pre_df.DAYSLATE.value_counts(normalize=True)


来源:https://stackoverflow.com/questions/44766208/add-column-for-percentage-of-total-to-pandas-dataframe

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