gpt4 book ai didi

python - 将前 X 行变成附加列 [Pandas]

转载 作者:行者123 更新时间:2023-11-30 21:51:03 24 4
gpt4 key购买 nike

例如,假设我有一列“a”

我想为每个样本/行提供指定量的先前值的“回溯”。例如,回顾 3 应该执行以下操作...

  a
0 1
1 2
2 3
3 4
4 5

a a1 a2 a3
0 1 Nan Nan Nan
1 2 1 Nan Nan
2 3 2 1 Nan
3 4 3 2 1
4 5 4 3 2

最佳答案

使用Series.shiftf-strings:

n = 3
for c in range(1, n+1):
df[f'a{c}'] = df['a'].shift(c)
print (df)
a a1 a2 a3
0 1 NaN NaN NaN
1 2 1.0 NaN NaN
2 3 2.0 1.0 NaN
3 4 3.0 2.0 1.0
4 5 4.0 3.0 2.0

列表理解的替代方案和 concat ,最后添加到原来的DataFrame.join :

n = 3
r = range(1, n+1)
df = df.join(pd.concat([df['a'].shift(c) for c in r], axis=1, keys=r).add_prefix('a'))
print (df)
a a1 a2 a3
0 1 NaN NaN NaN
1 2 1.0 NaN NaN
2 3 2.0 1.0 NaN
3 4 3.0 2.0 1.0
4 5 4.0 3.0 2.0

关于python - 将前 X 行变成附加列 [Pandas],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60209528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com