gpt4 book ai didi

Python 数据帧向量化 for 循环

转载 作者:行者123 更新时间:2023-12-02 02:32:46 24 4
gpt4 key购买 nike

我想使用以当前状态为条件的 for 循环对这段 Python 代码进行矢量化,以提高速度和效率。

df_B 的值是根据当前状态 (state) 和相应的 df_A 值计算的。

任何想法将不胜感激。

import pandas as pd
df_A = pd.DataFrame({'a': [0, 1, -1, -1, 1, -1, 0, 0] ,})
df_B = pd.DataFrame( data=0, index=df_A.index, columns=['b'])
print(df_A)

state = 0
for index, iter in df_A.iterrows():
if df_A.loc[index ,'a'] == -1:
df_B.loc[index ,'b'] = -10 -state
elif df_A.loc[index, 'a'] == 1:
df_B.loc[index, 'b'] = 10 - state
elif df_A.loc[index, 'a'] == 0:
df_B.loc[index, 'b'] = 0 - state
temp_state = state
state += df_B.loc[index, 'b']
print(df_B)

最佳答案

这似乎有点过分了。您的 state 变量基本上是 df_A['a']*10 中的先前值。所以我们可以使用 shift:

s = df_A['a'].mul(10) 

df_B['b'] = s - s.shift(fill_value=0)

关于Python 数据帧向量化 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64791873/

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