orbit
orbit

Reputation: 1296

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

Suppose, I have the following 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. For this example, the expected output is

 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?

Thanks in advance.

Upvotes: 3

Views: 102

Answers (2)

U13-Forward
U13-Forward

Reputation: 71580

Try apply and 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

Upvotes: 1

Shubham Sharma
Shubham Sharma

Reputation: 71689

Let's try boolean indexing with loc to filter the rows:

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

Upvotes: 3

Related Questions