【问题标题】:Pandas text matching like SQL's LIKE?Pandas 文本匹配像 SQL 的 LIKE?
【发布时间】:2023-03-11 21:43:01
【问题描述】:

有没有办法在 pandas 文本 DataFrame 列上执行类似于 SQL's LIKE syntax 的操作,以便返回索引列表或可用于索引数据帧的布尔值列表?例如,我希望能够匹配列以 'prefix_' 开头的所有行,类似于 SQL 中的WHERE <col> LIKE prefix_%

【问题讨论】:

    标签: pandas string-matching sql-like


    【解决方案1】:

    您可以使用Series方法str.startswith(采用正则表达式):

    In [11]: s = pd.Series(['aa', 'ab', 'ca', np.nan])
    
    In [12]: s.str.startswith('a', na=False)
    Out[12]: 
    0     True
    1     True
    2    False
    3    False
    dtype: bool
    

    您也可以对str.contains 执行相同操作(使用正则表达式):

    In [13]: s.str.contains('^a', na=False)
    Out[13]: 
    0     True
    1     True
    2    False
    3    False
    dtype: bool
    

    所以你可以这样做df[col].str.startswith...

    See also the SQL comparison section of the docs.

    注意:(正如 OP 所指出的)默认情况下,NaN 将传播(如果您想将结果用作布尔掩码,则会导致索引错误),我们使用此标志表示 NaN 应映射为 False。

    In [14]: s.str.startswith('a')  # can't use as boolean mask
    Out[14]:
    0     True
    1     True
    2    False
    3      NaN
    dtype: object
    

    【讨论】:

    • 感谢安迪。我还值得注意的是,在索引时使用,nans 会导致错误,因为它们默认返回 nan。您可以使用s.str.startswith('a', na=False) 强制他们返回 False。
    • @naught101 很好,其实我不知道!这很整洁。
    【解决方案2】:

    你可以使用

    s.str.contains('a', case = False)
    

    【讨论】:

      【解决方案3】:
      1. 要查找以模式“s”开头的系列中的所有值:

      SQL - WHERE column_name LIKE 's%'
      Python - column_name.str.startswith('s')

      1. 要查找以模式“s”结尾的系列中的所有值:

      SQL - WHERE column_name LIKE '%s'
      Python - column_name.str.endswith('s')

      1. 要从包含模式“s”的系列中查找所有值:

      SQL - WHERE column_name LIKE '%s%'
      Python - column_name.str.contains('s')

      更多选项,请查看:https://pandas.pydata.org/pandas-docs/stable/reference/series.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 2022-01-15
        • 2023-02-25
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        相关资源
        最近更新 更多