我有一个数据框如下
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
附言:
我知道可以通过如下输出来完成。但我正在寻找使用 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)]
最佳答案
您可以过滤掉“脚本”,然后使用应用函数来检查所需的字符串。
df.loc[df[[e for e in df.columns if e!='Script']].apply(lambda x: x.str.contains('Buy')).any(1)]
Script Reco Rating Suggestion Mood
0 Rel Buy Sell BuyL Sell
2 INFO Sell BuyN Sell Sell
关于python - 使用 FOR 循环完成 OR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899616/