1

i used groupby on a dataframe to get desired results. now Groupby result is a Series object and i want to convert into Dataframe. i have used Pd.Dataframe, but only Qty is coming as column output, Other columns from original table are coming as Index or series or tuple.

Original Dataframe

enter image description here

Desired output in Dataframe:

enter image description here

So first I used groupby to get sum of Qty:

StockSummary = StockSummary.groupby(['BussDate','Identifier'])['Qty'].sum()

then I tried below to get BussDate and Identifier as columns in a dataframe along with Qty. but no success. BussDate and Identifier are still coming as index/series/tuple in the dataframe.

StockSummary = pd.DataFrame(StockSummary)

StockSummary.reset_index()

used unstack() but that moves Bussdate values as columns and Identifier as 1 column. not looking for that solution

James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

1

You need to call to_frame since the result is a Pandas Series, then reset the index

df.groupby(['BussDate',  'Identifier'])['Qty'].sum().to_frame('Qty').reset_index()
   BussDate Identifier  Qty
0      2019        abc   33
1      2020        xyz  112
2      2021        abc  935

You can also use agg if you want to avoid calling to_frame:

df.groupby(['BussDate',  'Identifier']).agg({'Qty':sum}).reset_index()

   BussDate Identifier  Qty
0      2019        abc   33
1      2020        xyz  112
2      2021        abc  935
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45