python - 如何创建在其行中包含指定字符串的列列表?
问题描述
我有一个包含数百列的数据框,我想返回一组仅包含真/假字符串的列。
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
我的数据非常大,有什么办法可以优化这个搜索吗?
解决方案
您可以使用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')
推荐阅读
- swift - Swift如何在点击栏按钮时返回上一个视图控制器
- php - [PHP][MySQL] 如何同时在两张表中插入数据?
- python - Whatsapp 自动机器人无法在 WhatsApp 联系人列表中搜索
- macos - cron 作业无法在 macOS High Sierra 上运行
- mysql - 将 CASE WHEN 与另一个 CASE WHEN 一起使用的 MySQL 解决方案
- excel - 自动关闭工作簿
- python - python matplotlib中带有过滤条的交互式散点图
- sinch - 在后台接收 Sinch 消息和呼叫,并显示传入消息的通知并显示呼叫覆盖
- tig - 如何在 tig 中保存 refs 视图排序
- pycharm - 在 PyCharm 中搜索“TODO”不起作用