Suppose I have a df which has columns of 'ID', 'col_1', 'col_2'. And I define a function :

 f = lambda x, y : my_function_expression.

Now I want to apply the f to df's two columns 'col_1', 'col_2' to element-wise calculate a new column 'col_3' , somewhat like :  

df['col_3'] = df[['col_1','col_2']].apply(f)

How to do ?

译文:怎么同时对列 col_1 和 col_2 执行map操作,生成新的一列?

答:

Here's an example using apply on the dataframe, which I am calling with axis = 1.

Note the difference is that instead of trying to pass two values to the function f, rewrite the function to accept a pandas Series object, and then index the Series to get the values needed.

In [49]: df
Out[49]:
0 1
0 1.000000 0.000000
1 -0.494375 0.570994
2 1.000000 0.000000
3 1.876360 -0.229738
4 1.000000 0.000000 In [50]: def f(x):
....: return x[0] + x[1]
....: In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
Out[51]:
0 1.000000
1 0.076619
2 1.000000
3 1.646622
4 1.000000

Depending on your use case, it is sometimes helpful to create a pandas group object, and then use apply on the group.

译文:利用apply函数,在apply函数参数处指定自定义函数.自定义函数同时对多列进行计算,返回计算结果即可,详见代码.

来源:stackoverflow

最新文章

  1. yotaku的开发日志(1)
  2. Avg_row_length是怎么计算的?
  3. visual studio 2012 的制作ActiveX、打包和发布
  4. python watchdog
  5. Sybase IQ导出文件的几种方式
  6. SQL 数据库 触发器 、事务
  7. Facade 运行机制
  8. 这次一定理清晰ThinkPHP之中的模型、数据库之间命名规范
  9. 【Tech】android真机测试——小米3
  10. [转]AIX下调整分区大小
  11. failed to lazily initialize a collection of role
  12. WebConfig 配置文件详解
  13. HDU 5972 Regular Number(ShiftAnd+读入优化)
  14. CUSPARSE 第三章 CUSPARAE索引和数据格式
  15. 常用JavaScript字符串方法简述
  16. 一个Web前端自学者的自述
  17. 浅入javascript正则表达式的规则.
  18. Vue应用请求SpringBoot API出现 CORS 跨域请求设置 Invalid CORS request错误
  19. docker安装elasticsearch
  20. 项目管理目标:添加人员并向其分配任务 - Project

热门文章

  1. MySQL 5.7 for Windows 解压缩版配置安装
  2. zepto为什么不支持animate,报animate is not a function
  3. BCDedit 研究
  4. Sonya and Problem Wihtout a Legend
  5. POJ1611 The Suspects 并查集模板题
  6. 怎么把一个int数组转化为char型数组??
  7. 签名“未签名”apk文件命令
  8. IWorkSpace接口介绍
  9. jQuery + json 实现省市区三级联动
  10. Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3.0 ARMv7)