1

I am using groupby in the following code:

df=Output_Data.groupby(by=['Model', 'Year','State']).sum()

The resulting df looks like:

Model    Year    State  Data
A        2000    AL      10
                 AR       4
                 CA       8
A        2010    AL      23
                 AR      14
                 CA      32
B        2000    AL      11
                 AR       5
                 CA       9 

But what I want is the resulting df to look like:

Model    Year    State  Data
A        2000    AL      10
A        2000    AR       4
A        2000    CA       8
A        2010    AL      23
A        2010    AR      14
A        2010    CA      32
B        2000    AL      11
B        2000    AR       5
B        2000    CA       9 

I've dug around, but can't find a method or option to have the resulting df look like what I want. What's the best approach to achieve this?

jmark7453
  • 71
  • 1
  • 5
  • 5
    Use `.reset_index()` so full code: `df=Output_Data.groupby(by=['Model', 'Year','State']).sum().reset_index()` – David Erickson Jul 17 '20 at 23:20
  • This might also work and be a better way `df=Output_Data.groupby(by=['Model', 'Year','State'], as_index=False).sum()` - https://stackoverflow.com/questions/51866908/difference-between-as-index-false-and-reset-index-in-pandas-groupby I have not used `.as_index=False` before as an alternative to `reset_index()`, so I may have learned something myself here. – David Erickson Jul 17 '20 at 23:28

0 Answers0