检查熊猫列是否仅包含 0 或 1

Jos*_*ejo 3 python pandas

我想知道是否有办法检查熊猫列是否只包含 0 或 1。这可以通过使用df.groupby('col').count()然后验证只有两个索引并检查 0 和 1 是否是索引的一部分来完成。有没有更好的办法?

jez*_*ael 10

Series.isin如果所有值都是Trues by ,则与 test 一起使用Series.all

它返回TrueFalse标记。在这里查看它的实际效果。让我们考虑这个数据框:

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
Run Code Online (Sandbox Code Playgroud)