gpt4 book ai didi

python - 使用 Pandas 进行循环内的计算

转载 作者:行者123 更新时间:2023-12-05 00:42:36 25 4
gpt4 key购买 nike

我有这个数据集:

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),但可以工作。

预期的输出应该是:

expected 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 可以任意选择索引对齐的位置——这个序列应该从索引 0 还是 1 开始?但是您对问题的期望是它以 1 开头,就像这里的结果一样。

关于python - 使用 Pandas 进行循环内的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72840599/

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