![](/img/trans.png)
[英]How to select rows based on specific conditions of a range of columns in pandas
[英]How to select rows based on specific & conditions of a range of columns in pandas
假设,我有以下 dataframe:
A B C D E F
1 1 1 0 0 0
0 0 0 0 0 0
1 1 0.9 1 0 0
0 0 0 0 -1.95 0
0 0 0 0 2.75 0
1 1 1 1 1 1
我想要基于列C, D, E and F
的 select 行,这些行只有零和一( 0 & 1
)。 对于此示例,预期的 output 是
A B C D E F
1 1 1 0 0 0
考虑 pandas 中的一系列列,我该如何做到这一点?
提前致谢。
让我们尝试使用loc
进行 boolean 索引来过滤行:
c = ['C', 'D', 'E', 'F']
df.loc[df[c].isin([0, 1]).all(1) & df[c].eq(0).any(1) & df[c].eq(1).any(1)]
结果:
A B C D E F
0 1 1 1.0 0 0.0 0
尝试apply
和loc
:
print(df.loc[df.apply(lambda x: sorted(x.drop_duplicates().tolist()) == [0, 1], axis=1)])
Output:
A B C D E F
0 1 1 1.0 0 0.0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.