【问题标题】:How to filter a pandas column by list of strings?如何按字符串列表过滤熊猫列?
【发布时间】:2019-08-22 21:40:46
【问题描述】:

通过 pandas 进行过滤的标准代码类似于:

output = df['Column'].str.contains('string')
strings = ['string 1', 'string 2', 'string 3']

但是,我想过滤而不是“字符串”,以便它通过列表“字符串”中的字符串集合。所以我尝试了诸如

之类的东西
output = df['Column'].str.contains('*strings')

这是我能找到的最接近的解决方案,但没有奏效 How to filter pandas DataFrame with a list of strings

编辑:我应该注意我知道 |或运营商。但是,我想知道如何处理实例列表字符串中的所有情况正在发生变化,并且我正在循环遍历不同长度的变化列表作为最终目标。

【问题讨论】:

  • 您希望它包含strings 中的任何或所有字符串吗?
  • 请提供任何信息,但如果您不介意同时提供两者,那么无论如何都知道“全部”会很高兴
  • 试试regstr = '|'.join(strings)df['Column'].str.contains(regstr)

标签: python pandas list


【解决方案1】:

您可能应该考虑使用 isin() 函数 (pandas.Series.isin) 。

检查下面的代码:

    df = pd.DataFrame({'Column':['string 1', 'string 1', 'string 2', 'string 2', 'string 3', 'string 4', 'string 5']})
    strings = ['string 1', 'string 2', 'string 3']
    output = df.Column.isin(strings)

    df[output]

输出:

        Column
    0   string 1
    1   string 1
    2   string 2
    3   string 2
    4   string 3

【讨论】:

  • AttributeError: 'DataFrame' 对象没有属性 'Column'
  • 'Column' 是数据框中列的名称。执行 print(df) 以查看其结构和数据。 @bobo32
【解决方案2】:

您可以创建一个正则表达式字符串并使用该字符串进行搜索。

像这样: df['Column'].str.contains('|'.join(strings),regex=True)

【讨论】:

  • 这似乎有效。谢谢!我也刚刚找到 df['Column'].isin(strings)。结果似乎是一样的,但是你提供的代码有什么根本区别吗?
  • isin 将在列表中查找完全匹配的内容。 contains 将搜索包含您在列表中传递的字符串的文本,使用正则表达式查找它。例如:pd.Series(['string 1 foo']).isin(strings) 将返回 False。 pd.Series(['string 1 foo']).str.contains('|'.join(strings),regex=True) 将返回True
猜你喜欢
  • 1970-01-01
  • 2016-09-06
  • 2021-03-23
  • 2023-03-14
  • 2015-09-24
  • 2014-10-03
  • 2022-08-17
  • 2017-12-15
  • 2019-03-04
相关资源
最近更新 更多