[英]Shift Data and create new column - python dataframe
我正在研究一个问题,该问题需要将列中的数据移动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
预期的DataFrame:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.