【问题标题】:Accomplishing OR with a FOR loop用 FOR 循环完成 OR
【发布时间】: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 索引中。

标签: python string pandas


【解决方案1】:

您可以使用 stackany 创建布尔掩码

m = df.drop('Script',1).stack().str.contains('Buy').any(level=0)

Out[1021]:
0     True
1    False
2     True
3    False
dtype: bool

接下来,用它来切片

df[m]

Out[1022]:
  Script  Reco Rating Suggestion  Mood
0    Rel   Buy   Sell       BuyL  Sell
2   INFO  Sell   BuyN       Sell  Sell

【讨论】:

  • 谢谢。另一种方法(不使用 as for 循环)
【解决方案2】:

您可以过滤掉“脚本”,然后使用应用函数来检查所需的字符串。

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

【讨论】:

    【解决方案3】:

    按元素应用字符串包含检查可能更容易,然后使用.any 聚合结果。因此:

    df[cols_to_include].applymap(lambda x: 'Buy' in x).any(axis=1)

    【讨论】:

    • 这不起作用。这导致说明每列“['Reco', 'Rating', 'Suggestion', 'Mood']”是否具有购买价值。我想做的是行明智的。
    • 抱歉,我错过了轴参数。立即尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2015-08-15
    相关资源
    最近更新 更多