Home > Enterprise >  Create a new 100 % total column for every group
Create a new 100 % total column for every group

Time:09-23

I want to create a new column where every entry in the new column will be a portion of a percentage total from a group they belong to.

Before: enter image description here

for i in range(len(df7)):
    df7['perc'] = (df7[df7.loc[:, 'group'] == df7['group'][i]]['test']) / (df7[df7.loc[:, 'group'] == df7['group'][i]].test.sum())
    print(df7['perc'][i])

After: enter image description here

CodePudding user response:

Use Series.map with Series.value_counts and divide column:

df7['perc'] = df7['test'].div(df7['group'].map(df7['group'].value_counts()))

Alternative:

df7['perc'] = df7['test'].div(df7.groupby('group')['group'].transform('size'))
  • Related