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.
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])
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'))