pandas - How to use 2 parameters for apply-method in pandas
问题描述
a | b | c (2*a) | d (a+b) |
---|---|---|---|
a1 | b1 | 2*a1 | ???? |
a2 | b2 | 2*a2 | ???? |
I don't know how to calculate the column 'd(a+b)' which is used 2 parameters with apply method.
If I want the value of column 'c'(=2*a) which is only 1 parameter, I will script the following code.
def function(x):
ret = 2*x
return ret
df['c'] = df['a'].apply(function)
解决方案
在 lambda 中调用您的方法。
def function(a, b):
ret = a + b
return ret
df['d'] = df.apply(lambda row: function(row['a'], row['b']), axis=1)
或者
df['d'] = df.apply(lambda row: row['a'] + row['b'], axis=1)
简单地添加两列也可以
df['d'] = df['a'] + df['b']
推荐阅读
- mysql - 如何实现从返回多条记录的查询开始返回具有多列的单条记录的 SQL 查询?
- javascript - 放置按钮迭代列表
- c - 如何将文件中的数据加载到链表c中
- matlab - 使用树莓派包改进 Matlab 中函数的运行时间
- android - 某些Android Map API中特定区域下方的图形
- jenkins - 无法连接/设置一台 Windows 机器作为 Jenkins 从机/代理节点
- php - WordPress 和高级自定义字段管理,仪表板中的自定义列
- sql - Rails:在添加最后一个值时进行分组和求和(斐波那契)
- laravel - 用户的未定义属性 $id。但是用户有ID
- java - 从文本框中获取 Apache POI XSSFRichTextString