我正在解决一个问题,该问题需要将列中的数据移动1,2和3 ..并为此值创建新列。
示例数据框:
char str1[100] = "This is a string";
char temp[100];
int i;
for(i = 0; str1[i] != '\0'; i++){
temp[i] = str1[i];
}
temp[i] = '\0';
预期的DataFrame:
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
答案 0 :(得分:4)
首先使用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