【问题标题】:Filter rows from a dataframe从数据框中过滤行
【发布时间】:2020-08-14 09:42:54
【问题描述】:

我在数据框列中存储了一个字符串

import pandas as pd

df = pd.DataFrame({"ID": 1, "content": "froyay-xcd = (E)-cut-2-froyay-xcd"}, index=[0])
print(df)
idx = df[df['content'].str.contains("froyay-xcd  = (E)-cut-2-froyay-xcd")]
print(idx)

我正在尝试查找包含搜索字符串的行的索引,并出现以下警告

UserWarning: This pattern has match groups. To actually get the groups, use str.extract.
  return func(self, *args, **kwargs)

我不确定为什么当搜索字符串实际存在于数据框列中时会返回一个空数据框。

任何建议都将受到高度赞赏。我希望输出返回存储在数据框中的行。

【问题讨论】:

    标签: python-3.x pandas string dataframe


    【解决方案1】:

    您可以添加regex=False 参数以避免将值转换为正则表达式,这里() 是特殊的正则表达式字符:

    idx = df[df['content'].str.contains("froyay-xcd = (E)-cut-2-froyay-xcd", regex=False)]
    print(idx)
       ID                            content
    0   1  froyay-xcd = (E)-cut-2-froyay-xcd
    

    或者您可以通过以下方式转义正则表达式:

    import re
    
    idx = df[df['content'].str.contains(re.escape("froyay-xcd = (E)-cut-2-froyay-xcd"))]
    print(idx)
       ID                            content
    0   1  froyay-xcd = (E)-cut-2-froyay-xcd
    

    【讨论】:

      【解决方案2】:

      您可以在() 之前添加\ 以避免它,然后使用.index 获取索引

      df.content.str.contains("froyay-xcd = \(E\)-cut-2-froyay-xcd").index
      Int64Index([0], dtype='int64')
      

      如果你有更多的正则表达式特殊字符,最好使用@jezrael 所说的regex=False

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-12
        • 1970-01-01
        • 2020-03-16
        • 1970-01-01
        • 2018-08-13
        • 2016-08-11
        • 2019-03-29
        相关资源
        最近更新 更多