Python pandas: select columns with all zero entries in dataframe


Question

Given a dataframe how to find out all the columns that only have 0 as the values?

df
   0  1  2  3  4  5  6  7
0  0  0  0  1  0  0  1  0
1  1  1  0  0  0  1  1  1

Expected output

   2  4
0  0  0
1  0  0
1
16
10/5/2017 2:10:12 PM

Accepted Answer

I'd simply compare the values to 0 and use .all():

>>> df = pd.DataFrame(np.random.randint(0, 2, (2, 8)))
>>> df
   0  1  2  3  4  5  6  7
0  0  0  0  1  0  0  1  0
1  1  1  0  0  0  1  1  1
>>> df == 0
       0      1     2      3     4      5      6      7
0   True   True  True  False  True   True  False   True
1  False  False  True   True  True  False  False  False
>>> (df == 0).all()
0    False
1    False
2     True
3    False
4     True
5    False
6    False
7    False
dtype: bool
>>> df.columns[(df == 0).all()]
Int64Index([u'2', u'4'], dtype=int64)
>>> df.loc[:, (df == 0).all()]
   2  4
0  0  0
1  0  0
26
10/5/2017 2:11:30 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon