我想使用以当前状态为条件的 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/