2

I have a DataFrame that looks like this: Image

I need to calculate the percentage based on the count column which I already did following this answer.

The result is this:

Image2

Now I need to add the results for the Groupby column back into the original DataFrame. I tried grouped.reset_index() and then adding it but I get an error ValueError: cannot insert count, already exists since the column used in the Group by is also used in the aggregation.

Can anyone help me to find a way to add the results back to the DataFrame?

Community
  • 1
  • 1
Max Payne
  • 387
  • 3
  • 17

1 Answers1

1

You want to use transform and that answer you linked could be better as well.

df.assign(
    NormalizedCount=df['count'] / df.groupby('suburb')['count'].transform('sum')
piRSquared
  • 285,575
  • 57
  • 475
  • 624