5

I have a pandas.DataFrame with too much columns. I want to select all columns with values in rows equals to 0 and 1. Type of all columns is int64 and I can't select they by object or other type. How can I do this?

1 Answer 1

5

IIUC then you can use isin and filter the columns:

In [169]:
df = pd.DataFrame({'a':[0,1,1,0], 'b':list('abcd'), 'c':[1,2,3,4]})
df

Out[169]:
   a  b  c
0  0  a  1
1  1  b  2
2  1  c  3
3  0  d  4

In [174]:
df[df.columns[df.isin([0,1]).all()]]

Out[174]:
   a
0  0
1  1
2  1
3  0

The output from the inner condition:

In [175]:
df.isin([0,1]).all()

Out[175]:
a     True
b    False
c    False
dtype: bool

We can use the boolean mask to filter the columns:

In [176]:
df.columns[df.isin([0,1]).all()]

Out[176]:
Index(['a'], dtype='object')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.