首页 > 解决方案 > 在多列上使用 GroupBy 创建新的滚动平均列

问题描述

我有一个包含 11 列的数据框,其中之一date是索引。我正在尝试使用该列的滚动平均值创建一个新列total。但是,我收到错误:TypeError:插入列的索引与框架索引不兼容

import pandas as pd

df = pd.DataFrame({
    'date':['2016-04-01','2016-05-01','2016-07-01','2016-08-01','2016-09-01',  '2019-04-01','2019-05-01','2019-06-01','2019-08-01','2019-09-01'],
    'Country':['USA', 'USA', 'USA', 'USA', 'USA','USA', 'USA', 'USA', 'USA', 'USA'],
    'Region':['Eastern','Eastern','Eastern','Eastern','Eastern','Eastern','Eastern','Eastern','Eastern','Eastern'],
    'State':['New York','New York','New York','New York','New York','New York','New York','New York','New York','New York'],
    'Supplier':['ABC','ABC','ABC','ABC','ABC','ABC','ABC','ABC','ABC','ABC'],
    'Location':['Bin-1', 'Bin-1', 'Bin-1', 'Bin-1', 'Bin-1','Bin-1', 'Bin-1', 'Bin-1', 'Bin-1', 'Bin-1'],
    'Year':[2016,2016,2016,2016,2016,2019,2019,2019,2019,2019],
    'Month':[4,5,7,8,9,4,5,6,8,9],
    'periodcode':[4,5,7,8,9,4,5,6,8,9],
    'Product':['bike','bike','bike','bike','bike','bike','bike','bike','bike','bike'],
    'total':[0,2000,1000,4000,0,2000,2000,1000,4000,600]})
df.set_index('date', inplace=True)

df['mean'] = df.groupby(['Country','Region','State','Supplier','Location','Product'], as_index=False)['total'].rolling(3).mean().reset_index(level=0,drop=True)
df.head(10)

但是,当我将year列包含到groupbyie

df['mean'] = df.groupby(['Country','Region','State','Supplier','Location','Product','Year'], as_index=False)['total'].rolling(3).mean().reset_index(level=0,drop=True) 

我计算出滚动平均值。问题是,我希望分组排除Year

有任何想法吗?

标签: pythonpandaspandas-groupby

解决方案


由于根据我们在下面评论中的讨论,您希望计算每组多年来的滚动平均值,因此以下内容应为您提供所需的结果:

df['mean'] = df.groupby(['Country','Region','State','Supplier','Location','Product'])['total'].rolling(3).mean().reset_index().set_index("date")['total']

关键是保留date索引(它允许您将计算的滚动平均值与原始数据框中的一行匹配)并提取Series从 column 上的滚动平均值计算返回的对象total

更详细的解释:

您的问题是,groupby没有Year结果的 aDataFrame与不兼容df,因此不能分配给df["mean"].

第一个变体给出了一个Series女巫匹配索引:

df.groupby(['Country','Region','State','Supplier','Location','Product','Year'], as_index=False)['total'].rolling(3).mean().reset_index(level=0,drop=True)

date
2016-04-01            NaN
2016-05-01            NaN
2016-07-01    1000.000000
2016-08-01    2333.333333
2016-09-01    1666.666667
2019-04-01            NaN
2019-05-01            NaN
2019-06-01    1666.666667
2019-08-01    2333.333333
2019-09-01    1866.666667
Name: total, dtype: float64

但是,第二个变体(不带Year)导致列中的DataFrame每个条目都date成为其自己的列。因此,您不能将其分配给df["mean"].

此问题的解决方案实际上取决于您要解决的问题。但是,从概念上讲,如果您将索引作为索引,则您分配给date的每个只能有一个值。dateSeriesdf["mean"]


推荐阅读