【问题标题】:Identifying indices where any one of a plurality of columns has a certain value?识别多个列中的任何一个具有特定值的索引?
【发布时间】:2021-10-09 03:48:27
【问题描述】:

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

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

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

【问题讨论】:

  • 我想到的一个临时解决方案是创建一个单独的 df,仅过滤到感兴趣的列(df_temp = df[columns]),然后在任何列中找到值为 1 的任何行(df_temp .where(df_temp==1) ?)

标签: pandas filtering


【解决方案1】:

你可以试试这个:

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]

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2023-03-29
    • 2013-02-18
    • 2018-10-09
    • 2019-10-30
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多