Warm tip: This article is reproduced from stackoverflow.com, please click
django pandas python

Error when saving a dataframe group by pandas to django models

发布于 2020-03-27 15:45:16

I tried to create a dataframe grouped by pandas in django models, but got a KeyError as below

KeyError:'GoodsID'

I think there is a problem with the head of the dataframe column when doing groupby as below

                         Quantity  GoodsPrice
GoodsID GoodsIDSeqNo
G1      1                    1      1000.0
G2      2                    1         0.0
G3      1                    1         0.0
G4      1                    2      4000.0
        2                    1      1000.0
G5      2                    1         0.0
G6      1                    1      2000.0

How can I combine columns head in one row?

This is my code

sumifs_df = all_df.groupby([all_df['GoodsID'], all_df['GoodsIDSeqNo']]).sum()

for index, row in sumifs_df.iterrows():
        Sumifs.objects.create(GoodsID=row['GoodsID'], GoodsIDSeqNo=row['GoodsIDSeqNo'], Quantity=row['Quantity'], GoodsPrice=row['GoodsPrice'])
Questioner
user12666809
Viewed
17
sergiomahi 2020-01-31 17:18

When you create a grouped dataframe the columns you specified to group by become index of the grouped dataframe, so what you have to do is reset your index.

df = df_grouped.reset_index()