首页 > 解决方案 > 如何创建在其行中包含指定字符串的列列表?

问题描述

我有一个包含数百列的数据框,我想返回一组仅包含真/假字符串的列。

IE

a     b     c  d   e
true  false 34 cat true
false false 16 dog true
true  true  16 cow false

我希望返回 ['a', 'b', 'e']

我发现的所有堆栈溢出问题似乎都是在列标题中而不是在行值中搜索字符串。

一旦发现它包含一个真/假的例子,该列应该被添加到列表中,但我担心我必须搜索整个数据框,因为它可能包含许多 NULL

我的数据非常大,有什么办法可以优化这个搜索吗?

标签: pythonpandaslistdataframesubset

解决方案


您可以使用DataFrame.isin假设这些是字符串:

df.columns[df.isin(['true', 'false']).all()]
# Index(['a', 'b', 'e'], dtype='object')

如果它们确实是布尔 True/False 值,您可以使用select_dtypes

df.infer_objects().select_dtypes(bool).columns
# Index(['a', 'b', 'e'], dtype='object')

或者,简单过滤dtypes

df.columns[df.dtypes == bool]
# Index(['a', 'b', 'e'], dtype='object')

推荐阅读