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

Python 在DataFrame上选择具有条件的列,python,pandas,dataframe,conditional-statements,Python,Pandas,Dataframe,Conditional Statements,我有一个像这样的数据框 col1 col2 0 something1 something1 1 something2 something3 2 something1 something1 3 something2 something3 4 something1 something2 我正在尝试筛选所有在col1或col2上具有something1的行。如果我只需要一列上的条件逻辑,我可以使用df[df.col1=='something1']来实现

我有一个像这样的数据框

    col1    col2
0   something1  something1
1   something2  something3
2   something1  something1
3   something2  something3
4   something1  something2  
我正在尝试筛选所有在
col1
col2
上具有
something1
的行。如果我只需要一列上的条件逻辑,我可以使用
df[df.col1=='something1']
来实现,但是有没有一种方法可以使用多个列来实现呢?

您可以使用:

编辑:

如果需要,只选择一些可以用于选择所需
列的列,然后使用
子集
-
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
为什么不:

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

    col1    col2
0   something1  something1
2   something1  something1
4   something1  something2

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

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

谢谢你,耶斯雷尔!附加问题:如果我想筛选特定的列(比如,只在col1和col2中,但我有其他列),您知道怎么做吗?我想我需要用其他东西替换所有(1)?嗯,这些列有列名的公共部分?-
col
用于
col1
col2
?例如,如果我有col1、col2和col3,但我只想查看col1和col2,而不想查看col3。为什么不…?:):)
df[(df == 'something1').any(axis=1)]