我对 Python 还很陌生,有点卡住了。我需要将一列添加到包含列值的滚动差异的数据框中。但是,我需要以 3 为间隔重置此计数。我能做的最好的是
df['Value'].rolling(window=2).apply(lambda x: x[1] - x[0])
但我不知道如何重置差异计数。我尝试过 groupby,但没有结果。
手头的 table 看起来像这样
ID Location Year Value
01 EU 2000 42.402
02 EU 2001 44.336
03 EU 2002 46.477
04 US 2000 0.456
06 US 2001 0.438
07 US 2002 0.437
期望的结果应该如下所示:
ID Location Year Value RD
01 EU 2000 42.402 Null
02 EU 2001 44.336 1.934
03 EU 2002 46.477 2.141
04 US 2000 0.456 Null
06 US 2001 0.438 -0.124
07 US 2002 0.437 0.001
非常感谢。
最佳答案
使用 DataFrame.groupby
进行整数除以 3
的一般解决方案,使用 arange
按 DataFrame
的长度计算:
idx = np.arange(len(df)) // 3
#if default index
#idx = df.index // 3
s = df.groupby(idx)['Value'].rolling(window=2).apply(lambda x: x[1] - x[0], 'raw=False')
df['RD'] = s.reset_index(level=0, drop=True)
print (df)
ID Location Year Value RD
0 1 EU 2000 42.402 NaN
1 2 EU 2001 44.336 1.934
2 3 EU 2002 46.477 2.141
3 4 US 2000 0.456 NaN
4 6 US 2001 0.438 -0.018
5 7 US 2002 0.437 -0.001
关于python - 行间隔的滚动差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55215706/