python - 同时迭代两列并根据条件更改单元格的值
问题描述
我有以下格式的数据框:
指数 | Object1-长度 | Object1-高度 | Object2-长度 | Object2-高度 |
---|---|---|---|---|
0 | 19 | 49 | 21 | 52 |
1 | 20 | 50 | 21 | 51 |
2 | 20 | 51 | 20 | 52 |
3 | 19 | 50 | 19 | 52 |
4 | 20 | 50 | 20 | 52 |
它继续使用 Object3、Object4 等......
我想通过以下方式同时检查两列:
if ObjectX-Length >= 20 and ObjectX-Height >= 50
然后将 ObjectX 的两个单元格设置为 1,否则将它们设置为 0
所以这是我想要的表:
指数 | Object1-长度 | Object1-高度 | Object2-长度 | Object2-高度 |
---|---|---|---|---|
0 | 0 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 1 |
2 | 1 | 1 | 1 | 1 |
3 | 0 | 0 | 0 | 0 |
4 | 1 | 1 | 1 | 1 |
有没有办法做到这一点?
编辑:将每个对象的两列合并为一列并将该单元格设置为 0 或 1 也可以!
解决方案
咱们试试吧:
# length like columns
l = df.filter(like='-Length').columns
# corresponding height columns
h = l.str.rstrip('Length') + 'Height'
# create boolean mask
m = (df[l].ge(20).values & df[h].ge(50).values).astype(int)
# assign the values
df[h], df[l] = m, m
细节:
首先filter
是Length
like列,然后创建相应的Height
列:
print(l)
['Object1-Length', 'Object2-Length']
print(h)
['Object1-Height', 'Object2-Height']
创建表示条件的布尔掩码ObjectX-Length >= 20 and ObjectX-Height >= 50
:
print(m)
array([[0, 1],
[1, 1],
[1, 1],
[0, 0],
[1, 1]])
将掩码分配给相应的列:
print(df)
Object1-Length Object1-Height Object2-Length Object2-Height
Index
0 0 0 1 1
1 1 1 1 1
2 1 1 1 1
3 0 0 0 0
4 1 1 1 1
推荐阅读
- html - HTML5 视频 webOS
- javascript - 将 PNG 图像从后端保存到前端到本地 Angular 项目文件夹
- python - Python:从与其他元素同名的自闭合元素中提取属性
- c++ - 检索磁盘读/写最大速度(以编程方式)
- vue.js - in Vue:ElementUI的el-table中的cell-class-name和row-class-name是怎么实现的?
- java - 休眠分页错误接近极限 - SQL 服务器
- python - 在 Makefile 中使用环境变量作为 python 参数失败
- javascript - 如何在不声明的情况下使用新数组扩展数组
- linux - 用 pwd 和 awk 理解 shell 中的美元
- angular - Angular Subcribe - 类型 'Subscription' 缺少来自类型 'ToDo[]' 的以下属性:length、pop、push、concat 和另外 26 个