python - 使用 FOR 循环完成 OR

标签 python string pandas

我有一个数据框如下

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/

相关文章:

python - 错误: 'ColumnTransformer' object has no attribute '_n_features'

python - 验证 JSON 中的多个节点?

python - Python py2neo SocketError : Connection Refused

c++ - 是否可以将一个字符串的两个索引添加到一个字符,然后将该字符转换为 C++ 中的 int?

c# - 如何通过索引获取字符串中的字符?

c# - 将长字符串分成 60 个字符的长行但不要打断单词

python - 为什么我不能在 Pandas 系列生成的绘图上设置 y 轴范围?

python - Scrapy 爬虫不适用于网站,我得到部分结果

sorting - Pandas 数据透视表嵌套排序

python - 计算每行和每个索引的周年日期