[英]Python dataframe vectorizing for loop
I would like to vectorize this piece of python code with for loop conditioned on current state for speed and efficiency.我想使用以当前状态为条件的 for 循环向量化这段 python 代码,以提高速度和效率。
values for df_B are computed based on current-state ( state
) AND corresponding df_A value. df_B 的值是根据当前状态 (
state
) 和相应的 df_A 值计算的。
Any ideas would be appreciated.任何想法,将不胜感激。
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)
This seems overkill.这似乎太过分了。 Your
state
variable basically is the previous value in df_A['a']*10
.您的
state
变量基本上是df_A['a']*10
的先前值。 So we can just use shift
:所以我们可以使用
shift
:
s = df_A['a'].mul(10)
df_B['b'] = s - s.shift(fill_value=0)
You can make a class where state
is a class variable.您可以创建一个类,其中
state
是一个类变量。 This will allow you to write a function which can be fed to an apply
statement.这将允许您编写一个可以提供给
apply
语句的函数。 This isn't a vectorized solution, but it is faster than iterrows
.这不是矢量化解决方案,但它比
iterrows
快。 For example:例如:
class ComputeB:
def __init__(self, state=0):
self.state = state
def compute_b(self, row):
row["b"] = row["a"]*10 - self.state
self.state += row["b"]
return row
df = pd.concat([df_A, df_B], axis = 1)
cb = ComputeB()
df = df.apply(lambda row: cb.compute_b(row), axis = 1)
And now df["b"]
contains the values you wanted to compute.现在
df["b"]
包含您想要计算的值。 This does assume that df_A["a"]
can only contain 0, 1 and -1.这确实假设
df_A["a"]
只能包含 0、1 和 -1。 On my machine with a column of 40000 values the approach in the question took 10.4 seconds and this approach took 2.95 seconds.在我的机器上有一列 40000 个值,问题中的方法需要 10.4 秒,而这种方法需要 2.95 秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.