简体   繁体   English

如何根据 pandas 中列范围的特定 & 条件获取 select 行

[英]How to select rows based on specific & conditions of a range of columns in pandas

Suppose, I have the following dataframe:假设,我有以下 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

I want to select rows which have only zeros as well as ones ( 0 & 1 ) based on the columns C, D, E and F .我想要基于列C, D, E and F的 select 行,这些行只有零和一( 0 & 1 )。 For this example, the expected output is对于此示例,预期的 output 是

 A B C D E F
 1 1 1 0 0 0

How can I do this with considering a range of columns in pandas?考虑 pandas 中的一系列列,我该如何做到这一点?

Thanks in advance.提前致谢。

Let's try boolean indexing with loc to filter the rows:让我们尝试使用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)]

Result:结果:

   A  B    C  D    E  F
0  1  1  1.0  0  0.0  0

Try apply and loc :尝试applyloc

print(df.loc[df.apply(lambda x: sorted(x.drop_duplicates().tolist()) == [0, 1], axis=1)])

Output: Output:

   A  B    C  D    E  F
0  1  1  1.0  0  0.0  0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM