python - 遍历数据框中的每一行和每一列并对列值执行操作
问题描述
我有一个如下的 DataFrame,我想创建一个新列“Six”,这样该列的值取决于“Second”、“Third”、“Forth”、“Fifth”列值的值。如果 value = 1,则追加到第一列的值,如果 value = 0,则不执行任何操作。我可以知道怎么做吗?
Input :
First Second Third Forth Fifth
0 S1 1 0 0 0
1 S2 1 1 0 0
2 S3 1 1 0 0
Expected output
First Second Third Forth Fifth Six
0 S1 1 1 1 0 S1111
1 S2 1 1 0 0 S211
2 S3 1 1 1 0 S3111
解决方案
让我们试试这个:
df['Six'] = df.replace({1:'1', 0:''}).apply(''.join, axis=1)
输出:
First Second Third Forth Fifth Six
0 S1 1 0 0 0 S11
1 S2 1 1 0 0 S211
2 S3 1 1 0 0 S311
推荐阅读
- python - 部署在两个 VM 上的两个 Pod 相互通信的问题
- java - Spring Cloud Stream - 将 Serdes 提供给个人消费者/生产者
- css - SvgIcon 继承 viewBox
- c# - 使用统一容器获取 BusHealth 的实例
- julia - 在 Julia 中重复一个函数 N 次(组合)
- python - 从另一个文件导入类
- c# - 更改主机时从错误屏幕中删除 ASP.NET 版本信息
- r - 您如何(简单地)将函数应用于 R 中不同长度的多个子集?
- splunk - Splunk:如何对具有相同列值的多行应用条件?
- vue.js - 计算属性或其他方式根据 Vue 中 v-for 中的值更改样式