pandas - 识别多个列中的任何一个具有特定值的索引?
问题描述
我需要确定数据框中的哪些索引具有一组具有指定值的列中的任何一个。数据框有几百列,我需要使用几十列进行过滤,因此将它们全部写出来是不切实际的。我的策略如下,以确定名称中包含“temp”的任何列等于 1 的索引:
columns = [col for col in df.columns if 'temp' in col]
indices = list(np.where(df[columns]==1)[0])
但是,这会返回一个意外的结果 - 它似乎为 df 中的每个索引返回一个值。有什么线索会出错吗?
解决方案
你可以试试这个:
import pandas as pd
# Toy dataframe: two columns have "temp" in their name
# and rows 0 and 3 have a value of 1
df = pd.DataFrame(
{"SJDRtemp": [0, 0, 0, 1], "TR": [0, 0, 2, 1], "LDtemp": [1, 3, 0, 0]}
)
# Select columns which name contains "temp"
columns = [col for col in df.columns if "temp" in col]
# Get indices of rows where "temp columns" have a value of 1
indices = list(df[df[columns] == 1].dropna(how="all").index)
print(indices)
# Outputs
[0, 3]
推荐阅读
- python - 错误:未找到“登录”。“登录”不是有效的视图函数或模式名称
- java - 如何使用 Java 中另一个类的构造函数初始化 2D 数组?
- android - Renderscript:加载 ScriptC 脚本失败
- amazon-web-services - CloudFront + Amazon WAF 与另一台主机
- php - 如何获取 client_max_body_size (nginx - php-fpm) 作为 PHP 中的值?
- xml - 如何使用 XML::LibXML 返回单独的结果
- html - 网页中的声音输入
- azure-devops - 从 VSTS 压缩部署到 Azure Functions v2 后,DurableTask 未注册
- android - Android联系人合同:是否可以获得数据行的唯一ID?
- python - Python: Cosine similarity between two large numpy arrays