检查pandas列是否仅包含0或1

4

我想知道是否有一种方法可以检查pandas列中是否仅包含0或1。可以使用df.groupby('col').count()来完成此操作,然后验证只有两个索引并检查0和1是否是索引的一部分。是否有更好的方法?

3个回答

15

使用Series.isin与测试,如果所有值都为True则使用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

0
你可以使用unique()函数,它会返回某一列中所有唯一的值。
例如:
#List unique values in the df['name'] column
df.name.unique()

这将返回该列中存在的唯一值数组。

0

您可以使用set操作与set.issubset

{0, 1}.issuperset(df['col'])

例子:

df = pd.DataFrame({'col': [0, 1, 0]})

{0, 1}.issuperset(df['col'])
# True

如果您有多列:
df = pd.DataFrame({'A': [0, 1, 2],
                   'B': [1, 1, 1],
                   'C': [0, 1, 0]})

df.apply({0, 1}.issuperset)
# A    False
# B     True
# C     True
# dtype: bool

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接