Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pandas,如何在使用groupby()时创建完全填充的DF_Python_Pandas - Fatal编程技术网

Python Pandas,如何在使用groupby()时创建完全填充的DF

Python Pandas,如何在使用groupby()时创建完全填充的DF,python,pandas,Python,Pandas,我试图用从更大的df中提取的计算需求值填充数据帧。其目的是了解特定变量的行为(时间需求) 如果我使用df1.groupby(['product\u title','supplier\u name','date'])['difference'].sum().fillna(0) 我得到以下结果: product_title supplier_name date Adults-Blue (mask) WEI 06/03/20 5

我试图用从更大的df中提取的计算需求值填充数据帧。其目的是了解特定变量的行为(时间需求)

如果我使用
df1.groupby(['product\u title','supplier\u name','date'])['difference'].sum().fillna(0)
我得到以下结果:

product_title       supplier_name date  
Adults-Blue (mask)  WEI           06/03/20  5
                                  06/05/20  1
                    iYV           06/04/20  3
                                  06/05/20  4
                                  06/07/20  2
但我需要的结果是以下结果(1):

product_title       supplier_name date      demand
Adults-Blue (mask)  WEI           06/03/20  5
Adults-Blue (mask)  WEI           06/05/20  1
Adults-Blue (mask)  iYV           06/04/20  3
Adults-Blue (mask)  iYV           06/05/20  4
Adults-Blue (mask)  iYV           06/07/20  2
我还尝试使用以下方法在原始数据框中创建一个新列:

df1['demand'] = df1.groupby(['product_title', 'supplier_name', 'date'])['difference'].sum().fillna(0)
但我得到一个索引错误:

TypeError: incompatible index of inserted column with frame index

可以理解,因为我正在生成一个更小的数据帧。我该怎么做才能得到结果(1)?

我编造了一些玩具数据来给你一些工作代码。如前所述,您可以使用
reset\u index
,但这需要比此解决方案更多的代码。这是你怎么做的

import pandas as pd
df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
                              'Parrot', 'Parrot'],
                   'Max Speed': [380., 370., 24., 26.]})

df['mean_speed_animal'] = df.groupby(['Animal']).transform('sum').fillna(0)
print(df)

可以添加原始数据帧的示例吗?在所有操作之后执行
.reset_index()
,因为group by使用group by的键作为分组结果中的索引。重置索引将把它们作为单独的值再次放在列中。由于您的建议,我解决了这个问题:df1['demand']=df1.groupby(['product\u title','supplier\u name','date'])['difference'].transform('sum')。fillna(0)很高兴我能提供帮助!