gpt4 book ai didi

python - 移动数据并创建新列 - python 数据框

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:43 25 4
gpt4 key购买 nike

我正在解决一个问题,它需要将列中的数据移动 1,2 和 3 ..并为该值创建新列。

示例数据框:

Date     Price 
1-1-18 10
2-1-18 20
3-1-18 25
4-1-18 30
5-1-18 45
6-1-18 50
7-1-18 60

预期的数据帧:

Date    Price    Price1    Price2    Price3
1-1-18 10 -1 -1 -1
2-1-18 20 -1 -1 -1
3-1-18 25 -1 -1 -1
4-1-18 30 25 20 10
5-1-18 45 30 25 20
6-1-18 50 45 30 25
7-1-18 60 50 45 30

最佳答案

首先使用 shift 创建新列按范围然后设置-1:

N = 3
for x in range(1, N + 1):
#python 3.6+
df[f'Price{x}'] = df['Price'].shift(x)
#python bellow
#df['Price{}'.format(x)] = df['Price'].shift(x)

df.iloc[:N, -N:] = -1
print (df)
Date Price Price1 Price2 Price3
0 1-1-18 10 -1.0 -1.0 -1.0
1 2-1-18 20 -1.0 -1.0 -1.0
2 3-1-18 25 -1.0 -1.0 -1.0
3 4-1-18 30 25.0 20.0 10.0
4 5-1-18 45 30.0 25.0 20.0
5 6-1-18 50 45.0 30.0 25.0
6 7-1-18 60 50.0 45.0 30.0

关于python - 移动数据并创建新列 - python 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54231028/

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