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?
Use Series.isin
with test if all values are True
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With