Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if pandas column contains only 0's or 1's

Tags:

python

pandas

I want to know if there is a way to check whether a pandas column contains only 0's or 1's. This can be done using df.groupby('col').count() and then verifying that there are only two indices and checking if 0 and 1 are part of the index. Is there a better way?

like image 880
José Vallejo Avatar asked Dec 11 '22 01:12

José Vallejo


1 Answers

Use Series.isin with test if all values are Trues by Series.all:

It returns True or False flag. See it in action here.Let's consider this dataframe:

df = pd.DataFrame({'col1':[0,1,0],
                   'col2':[2,3,1]})
print (df)
   col1  col2
0     0     2
1     1     3
2     0     1

test = df['col1'].isin([0,1]).all()
True

test = df['col2'].isin([0,1]).all()
False
like image 183
jezrael Avatar answered Dec 30 '22 02:12

jezrael