[英]Calculations inside loop with pandas
我有这个数据集:
data = {
'index': [4, 17, 24, 36, 42],
'High': [805.000000, 1094.939941, 1243.489990, 1201.949951, 1172.839966],
}
我想得到一个斜坡,比如:
test = pd.DataFrame(data)
for i in range(len(test)):
test.loc[:,'slope'] = (test.loc[i+1,'High'] - test.loc[i,'High']) / (test.loc[i+1,'index'] - test.loc[i,'index'])
print(test)
似乎我要超出循环的边界,但是我该如何编码才能使第一行空白并填充下一行?
如果我在没有 +1 的情况下执行相同的代码并使用 i 来代替它,它会给出 0/0(Nan),但可以。
预期的 output 应该是:
一个整列的计算方法是这样的:
我们可以使用diff
与之前的值进行一系列差异:
test['index'].diff()
0 NaN
1 13.0
2 7.0
3 12.0
4 6.0
Name: index, dtype: float64
使用它,我们可以计算每步索引差异的高差异:
test['High'].diff() / test['index'].diff()
0 NaN
1 22.303072
2 21.221436
3 -3.461670
4 -4.851664
dtype: float64
IMO 关于索引 alignment 应该在哪里的任意选择 - 这个序列应该从索引 0 还是 1 开始? 但是您对问题的期望是它以 1 开头,就像这里的结果一样。
只需从范围中减去 1,因此 for 循环不会 go 超出边界
for i in range(len(test)-1):
test.loc[i+1,'slope'] = round((test.loc[i+1,'High'] - test.loc[i,'High']) / (test.loc[i+1,'index'] - test.loc[i,'index']),2)
更好的解决方案是使用 Shift function,因为对于大型数据集,for 循环将花费更长的时间 -
test['slope'] = round((test['High']-test['High'].shift(1)) / (test['index']-test['index'].shift(1)),2)
test
只需给它一个条件,如果索引为零,则跳过它并稍微更改计算。 我也发现了一些人为错误,你输入test.loc[:,'slope']
而不是test.loc[i,'slope']
for i in range(len(test)):
test.loc[i,'slope'] = 0 if i==0 else (test.loc[i,'High'] - test.loc[i-1,'High']) / (test.loc[i,'index'] - test.loc[i-1,'index'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.