首页 > 解决方案 > Using lambda functions with apply for Pandas DataFrame

问题描述

I am sorry for asking such a trivial question, but I keep making mistakes when using the apply function with a lambda function that has input parameters.

See below:

df = pd.DataFrame([["John",1,3],["James",2,3],
            ["Femi",3,4], ["Rita",3,3],
            ["Rita",3,3]], columns=["Name","Age","Height"])


%timeit df["product_AH"] = df[["Age", "Height"]].apply(lambda x,y: x['Age']*y['Height'], axis=1)

Expected output:

    Name    Age  Height  product_AH
0   John    1     3          3
1   James   2     3          6
2   Femi    3     4          12
3   Rita    3     3          9
4   Rita    3     3          9

标签: pythonpandasdataframe

解决方案


如果您必须使用“应用”变体,则代码应为:

df['product_AH'] = df.apply(lambda row: row.Age * row.Height, axis=1)

应用函数的参数是整行。

但更快的解决方案是:

df['product_AH'] = df.Age * df.Height

(1.43 毫秒,而“应用”变体为 5.08 毫秒)。

这种方式计算是使用向量化执行的,而apply 分别引用每一行,将函数应用于它,然后组合所有结果并将它们保存在目标列中,这要慢得多。


推荐阅读