简体   繁体   English

在 Pandas DataFrame 上选择具有条件的列

[英]Selecting columns with condition on Pandas DataFrame

I have a dataframe looking like this.我有一个看起来像这样的数据框。

    col1    col2
0   something1  something1
1   something2  something3
2   something1  something1
3   something2  something3
4   something1  something2  

I'm trying to filter all rows that have something1 either on col1 or col2 .我正在尝试过滤在col1col2上有something1所有行。 If I just need the condition logic on a column, I can do it with df[df.col1 == 'something1'] but would there be a way to do it with multiple columns?如果我只需要列上的条件逻辑,我可以用df[df.col1 == 'something1']来做,但是有没有办法用多列来做?

You can use all with boolean indexing :您可以将allboolean indexing一起使用:

print ((df == 'something1').all(1))
0     True
1    False
2     True
3    False
4    False
dtype: bool

print (df[(df == 'something1').all(1)])
         col1        col2
0  something1  something1
2  something1  something1

EDIT:编辑:

If need select only some columns you can use isin with boolean indexing for selecting desired columns and then use subset - df[cols] :如果需要选择某些列,您可以使用isinboolean indexing选择所需的columns ,然后使用subset - df[cols]

print (df)
         col1        col2 col3
0  something1  something1    a
1  something2  something3    s
2  something1  something1    r
3  something2  something3    a
4  something1  something2    a

cols = df.columns[df.columns.isin(['col1','col2'])]
print (cols)
Index(['col1', 'col2'], dtype='object')

print (df[(df[cols] == 'something1').all(1)])
         col1        col2 col3
0  something1  something1    a
2  something1  something1    r

Why not:为什么不:

df[(df.col1 == 'something1') | (df.col2 == 'something1')]

outputs:输出:

    col1    col2
0   something1  something1
2   something1  something1
4   something1  something2

将一个条件应用于整个数据框

df[(df == 'something1').any(axis=1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM