同时迭代两列并根据条件更改单元格的值
我有以下格式的数据框:
| 指数 | 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 |
回答
咱们试试吧:
# 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喜欢的列,然后创建相应的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