python - 行间隔的滚动差异

标签 python pandas numpy

我对 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 的一般解决方案,使用 arangeDataFrame 的长度计算:

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/

相关文章:

python - 如何从 Python Azure Function App 查看错误日志?

python - Pandas "Group By"查询 HDFStore 中的大数据?

python-3.x - 如何对齐 pandas 中的输出

python - 为什么重新索引后会显示 nan 值?

python - 将 Flask 上传的文件读取到 pandas 数据框中时找不到文件

python - 如何将数组列表拆分为单独的数组?

python-3.x - 优雅地将int64的numpy数组转换为datetime64的numpy数组

Python Scraper无法在mysql数据库中保存度数符号°

python - 使用 block 大小将 CSV 文件从 s3 加载到 Pandas

python - Pygame Sprite 旋转太快