gpt4 book ai didi

python - 检查 pandas 列是否仅包含 0's or 1' s

转载 作者:行者123 更新时间:2023-12-03 01:52:57 25 4
gpt4 key购买 nike

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

最佳答案

使用Series.isin通过 Series.all 测试所有值是否为 True :

它返回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

关于python - 检查 pandas 列是否仅包含 0's or 1' s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60278036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com