python dataframe 针对多列执行map操作
2024-10-19 04:28:31
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函数参数处指定自定义函数.自定义函数同时对多列进行计算,返回计算结果即可,详见代码.
最新文章
- yotaku的开发日志(1)
- Avg_row_length是怎么计算的?
- visual studio 2012 的制作ActiveX、打包和发布
- python watchdog
- Sybase IQ导出文件的几种方式
- SQL 数据库 触发器 、事务
- Facade 运行机制
- 这次一定理清晰ThinkPHP之中的模型、数据库之间命名规范
- 【Tech】android真机测试——小米3
- [转]AIX下调整分区大小
- failed to lazily initialize a collection of role
- WebConfig 配置文件详解
- HDU 5972 Regular Number(ShiftAnd+读入优化)
- CUSPARSE 第三章 CUSPARAE索引和数据格式
- 常用JavaScript字符串方法简述
- 一个Web前端自学者的自述
- 浅入javascript正则表达式的规则.
- Vue应用请求SpringBoot API出现 CORS 跨域请求设置 Invalid CORS request错误
- docker安装elasticsearch
- 项目管理目标:添加人员并向其分配任务 - Project
热门文章
- MySQL 5.7 for Windows 解压缩版配置安装
- zepto为什么不支持animate,报animate is not a function
- BCDedit 研究
- Sonya and Problem Wihtout a Legend
- POJ1611 The Suspects 并查集模板题
- 怎么把一个int数组转化为char型数组??
- 签名“未签名”apk文件命令
- IWorkSpace接口介绍
- jQuery + json 实现省市区三级联动
- Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3.0 ARMv7)