标识索引,其中任何一个列有一定的值?



我需要确定数据框架中的哪些索引具有具有指定值的一组列中的任何一个。数据框有几百列,其中有几十列需要用于过滤,因此将它们全部写出来是不切实际的。我的策略如下,以确定任何列的名称中有'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]

最新更新