考虑这个简单的例子
df = pd.DataFrame({'date' : [pd.to_datetime('2018-01-01'),
pd.to_datetime('2018-01-01'),
pd.to_datetime('2018-01-01'),
pd.to_datetime('2018-01-01')],
'group' : ['a','a','b','b'],
'value' : [1,2,3,4],
'value_useless' : [2,2,2,2]})
df
Out[78]:
date group value value_useless
0 2018-01-01 a 1 2
1 2018-01-01 a 2 2
2 2018-01-01 b 3 2
3 2018-01-01 b 4 2
在这里,我想要按组计算value
的滚动和。我试着用简单的
df['rolling_sum'] = df.groupby('group').value.rolling(2).sum()
TypeError: incompatible index of inserted column with frame index
带有apply
的变体似乎也不起作用
df['rolling_sum'] = df.groupby('group').apply(lambda x: x.value.rolling(2).sum())
TypeError: incompatible index of inserted column with frame index
这里我漏掉了什么?谢谢!
https://stackoverflow.com/questions/52264035
复制相似问题