问题描述
我正在尝试迭代一个数据框并在每次迭代时更新前一行。我的索引是基于日期的。
for i,row in df.iterrows():
# do my calculations here
myValue = row['myCol']
prev = row.shift()
prev['myCol'] = prev['myCol'] - myValue
没有错误但没有保存,我该如何保存?
解决方法
如果没有示例数据,就不清楚您在尝试什么。但是使用您的 for
循环中的操作,它可以可能像这样完成,而不需要任何循环:
myValue = df['myCol'] # the column you wanted and other calculations
df['myCol'] = df['myCol'].shift() - myValue
根据您的尝试,其中之一应该是您想要的:
# starting with this df
myCol otherCol
0 2 6
1 9 3
2 4 8
3 2 8
4 1 7
# next row minus current row
df['myCol'] = df['myCol'].shift(-1) - df['myCol']
df
# result:
myCol otherCol
0 7.0 6
1 -5.0 3
2 -2.0 8
3 -1.0 8
4 NaN 7
或
# previous row minus current row
df['myCol'] = df['myCol'].shift() - df['myCol']
df
# result:
myCol otherCol
0 NaN 6
1 -7.0 3
2 5.0 8
3 2.0 8
4 1.0 7
而 myVal
可以是任何东西,比如对整个列进行矢量化的一些数学运算:
myVal = df['myCol'] * 2 + 3
# myVal is:
0 7
1 21
2 11
3 7
4 5
Name: myCol,dtype: int32
df['myCol'] = df['myCol'].shift(-1) - myVal
df
myCol otherCol
0 2.0 6
1 -17.0 3
2 -9.0 8
3 -6.0 8
4 NaN 7