Reputation: 1296
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
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
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