首页 > 解决方案 > 识别多个列中的任何一个具有特定值的索引?

问题描述

我需要确定数据框中的哪些索引具有一组具有指定值的列中的任何一个。数据框有几百列,我需要使用几十列进行过滤,因此将它们全部写出来是不切实际的。我的策略如下,以确定名称中包含“temp”的任何列等于 1 的索引:

columns = [col for col in df.columns if 'temp' in col]
indices = list(np.where(df[columns]==1)[0])

但是,这会返回一个意外的结果 - 它似乎为 df 中的每个索引返回一个值。有什么线索会出错吗?

标签: pandasfiltering

解决方案


你可以试试这个:

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]

推荐阅读