Python 数据帧中的哪些列是二进制的?

Python 数据帧中的哪些列是二进制的?,python,numpy,pandas,Python,Numpy,Pandas,我有一个包含大量列的数据框架,我需要在不查看数据的情况下找到哪些列是二进制的(仅值为0或1)。应该使用哪个函数?据我所知,没有直接的函数可供测试。相反,您需要根据数据的编码方式(例如1/0、T/F、True/False等)构建一些内容。此外,如果列缺少值,则整个列将被编码为浮点而不是int 在下面的示例中,我测试所有唯一的非空值是“1”还是“0”。它返回所有此类列的列表 df = pd.DataFrame({'bool': [1, 0, 1, None],

我有一个包含大量列的数据框架,我需要在不查看数据的情况下找到哪些列是二进制的(仅值为0或1)。应该使用哪个函数?

据我所知,没有直接的函数可供测试。相反,您需要根据数据的编码方式(例如1/0、T/F、True/False等)构建一些内容。此外,如果列缺少值,则整个列将被编码为浮点而不是int

在下面的示例中,我测试所有唯一的非空值是“1”还是“0”。它返回所有此类列的列表

df = pd.DataFrame({'bool': [1, 0, 1, None], 
                   'floats': [1.2, 3.1, 4.4, 5.5], 
                   'ints': [1, 2, 3, 4], 
                   'str': ['a', 'b', 'c', 'd']})

bool_cols = [col for col in df 
             if df[[col]].dropna().unique().isin([0, 1]).all().values]

# 2019-09-10 EDIT (per Hardik Gupta)
bool_cols = [col for col in df 
             if np.isin(df[col].dropna().unique(), [0, 1]).all()]

>>> bool_cols
['bool']

>>> df[bool_cols]
   bool
0     1
1     0
2     1
3   NaN

要扩展上面的答案,使用value_counts().index而不是unique()应该可以做到:

bool_cols = [col for col in df if 
               df[col].dropna().value_counts().index.isin([0,1]).all()]

改进@Aiden以避免返回空列:

[col for col in df if (len(df[col].value_counts()) > 0) & all(df[col].value_counts().index.isin([0, 1]))]

这是我找到的最有效的解决方案。这比上面的答案快。在处理大型数据集时,时间上的差异变得相关。

使用Alexander的答案,使用python版本-3.6.6

[col for col in df if np.isin(df[col].unique(), [0, 1]).all()]

您只需在数据集中的每一列上使用pandas中的unique()函数

例如:
df[“colname”].unique()

这将返回指定列中所有唯一值的列表

还可以使用for循环遍历数据集中的所有列


示例:
[df[cols].df中cols的唯一性()

谢谢@Alexander。工作!有效,除了
.unique()
0.18.1
中似乎无效之外。一个隐藏的技巧是,这适用于显式布尔的列,即
False
True
,而不仅仅是
0
1
。这是因为python显然是自动强制转换的<[0,1]中的code>False返回
True
[col for col in df if np.isin(df[col].unique(),[0,1]).all()][/code>,这应该被更新回答这将传递给没有值的列,因为
all
在空列表中返回
True
。我认为这并不可取。在调用
.unique()
之前,您首先需要
.dropna()
,但感谢您的更新。
[col for col in df if np.isin(df[col].unique(), [0, 1]).all()]