gpt4 book ai didi

具有更新值的python for循环

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:20 24 4
gpt4 key购买 nike

我有一个超过 10k 行的 pandas 数据框。我需要遍历每一行并根据更新后的前一行的值进行数学运算。 For 循环非常慢。

示例 DF:

a  b  c
1 2 3
2 3 4
3 4 5

for 循环示例:

for i in range(1,len(DF)):
DF['b'] = DF['b'].[i-1]+DF['c']

我也试过

DF['b'] = DF['b'].shift(1)+DF['c']

但这不会使用更新后的值“b”。

进行此类计算的最佳方法是什么?

回答:loc 和 iloc 有帮助。最好的方法是:

for i in range(1, len(DF)):
DF.loc[i, 'b'] = DF.loc[i-1, 'b'] + DF.loc[i, 'c']

最佳答案

使用 iloc

for i in range(1,len(DF)):
DF.iloc[i]['b'] = DF.iloc[i-1]['b']+DF.iloc['i']['c']

关于具有更新值的python for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30989064/

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