pyt*_*rtz 3 python multiple-columns dataframe pandas
我有以下格式的数据框:
指数 | 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
Run Code Online (Sandbox Code Playgroud)
然后将 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
Run Code Online (Sandbox Code Playgroud)
细节:
首先filter
是Length
喜欢的列,然后创建相应的Height
列:
print(l)
['Object1-Length', 'Object2-Length']
print(h)
['Object1-Height', 'Object2-Height']
Run Code Online (Sandbox Code Playgroud)
创建表示以下条件的布尔掩码ObjectX-Length >= 20 and ObjectX-Height >= 50
:
print(m)
array([[0, 1],
[1, 1],
[1, 1],
[0, 0],
[1, 1]])
Run Code Online (Sandbox Code Playgroud)
将掩码分配给相应的列:
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
Run Code Online (Sandbox Code Playgroud)