python - 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
解决方案
如果您必须使用“应用”变体,则代码应为:
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 分别引用每一行,将函数应用于它,然后组合所有结果并将它们保存在目标列中,这要慢得多。
推荐阅读
- c# - 代理后面的 C# UpdateSession (WUApi.dll)
- python - 如何在 python 中使用自定义比较器函数对 2D 列表进行排序?
- java - 如果 bean 列表为空,OpenCSV 不会写入标题
- c - C创建一个非二进制的PID文件
- html - 如何使用 css-grid 设置表单输入的样式以跨越上述起始项目的整个长度并正确缩放
- wordpress - Wordpress 的简单付款表格
- git - 无法使用 Gitlab Ci 部署两个存储库
- python - 从列表中查询,从字典的字典中返回
- go - 这三种创建DIY结构的方法有什么区别?
- hyperledger-fabric - hyperledger fabric 2.2,无法将orderer添加到现有网络