简体   繁体   English

带有功能的Pandas DataFrame逐行公式

[英]Pandas dataframe row-wise formula with function

So I have quite big DataFrame and I create a new column by some equation based on other columns: 所以我有相当大的DataFrame,并根据其他列根据一些方程式创建了一个新列:

df['F'] = (params.a * params.b * df.A/1000 - param.C * (df.B + df.C - df.D) + param.D * df.E

and it works perfectly fine. 而且效果很好。 Except I want to repeat this function throughout the code , so instead of error-prone copying and pasting I want to cast it into a reusable function. 除了要在整个代码中重复此功能之外 ,因此我不想将其易于复制和粘贴,而是将其强制转换为可重用的功能。

So I casted it into lambda: 所以我将其转换为lambda:

def fun(r):
     return (params.a * params.b * r.A/1000 - param.C * (r.B + r.C - r.D) + param.D * r.E   
df['F'] = r.apply(funy,axis =1)

yet this is 5x slower now ( 1.2s vs 6s for 10k rows). 但这现在了5倍(对于1万行,是1.2秒与6秒 )。

What should I do if I want to have a neat function and still benefit from speed? 如果我想拥有整洁的功能并且仍然受益于速度,该怎么办?

What's wrong with: 有什么问题:

def fun():
    return params.a * params.b * df.A/1000 - param.C * (df.B + df.C - df.D) + param.D * df.E

df['F'] = fun()

So you get a reusable vectorized function. 因此,您将获得可重用的矢量化函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM