【发布时间】:2020-01-13 21:54:09
【问题描述】:
我有一个如下的数据框
Script Reco Rating Suggestion Mood
Rel Buy Sell BuyL Sell
ITC Sell Sell Sell Sell
INFO Sell BuyN Sell Sell
TCS Sell Sell Sell Sell
我想在“Reco”、“Rating”、“Suggestion”或“Mood”列中获取字符串“Buy”的行。
我可以用下面的代码来完成它
df[(df['Reco'].str.contains('Buy', regex=True) | df['Rating'].str.contains('Buy', regex=True) | df['Suggestion'].str.contains('Buy', regex=True) | df['Mood'].str.contains('Buy', regex=True))]
但是,问题是我必须输入除“脚本”之外的所有列的名称。为避免这种情况,请尝试执行以下操作
cols_to_include = df.columns[df.columns != 'Script']
df[(df[i].str.contains('Buy') for i in cols_to_include)]
这不起作用&那是因为
(df['Reco'].str.contains('Buy', regex=True) | df['Rating'].str.contains('Buy', regex=True) | df['Suggestion'].str.contains('Buy', regex=True) | df['Mood'].str.contains('Buy', regex=True))
返回
0 True
1 False
2 True
3 False
dtype: bool
而
[df[i].str.contains('Buy') for i in cols_to_include]
返回
[0 True
1 False
2 False
3 False
Name: Reco, dtype: bool, 0 False
1 False
2 True
3 False
Name: Rating, dtype: bool, 0 True
1 False
2 False
3 False
Name: Suggestion, dtype: bool, 0 False
1 False
2 False
3 False
Name: Mood, dtype: bool]
如何让[df[i].str.contains('Buy') for i in cols_to_include] 返回如下值?
0 True
1 False
2 True
3 False
dtype: bool
PS:
我知道可以通过如下输出来完成。但我正在寻找使用for 循环的解决方案。
cols_to_include = df.columns[df.columns != 'Script']
a = df[cols_to_include].astype(str).sum(axis=1)
df[a.str.contains('BUY', regex=True)]
【问题讨论】:
-
|应该是or。 -
@Barmar 不在 pandas 索引中。