Add column for percentage of total to Pandas dataframe

AlliDeacon picture AlliDeacon · Jun 26, 2017 · Viewed 15.2k times · Source

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

Answer

piRSquared picture piRSquared · Jun 26, 2017

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)