【发布时间】:2023-03-11 21:43:01
【问题描述】:
有没有办法在 pandas 文本 DataFrame 列上执行类似于 SQL's LIKE syntax 的操作,以便返回索引列表或可用于索引数据帧的布尔值列表?例如,我希望能够匹配列以 'prefix_' 开头的所有行,类似于 SQL 中的WHERE <col> LIKE prefix_%。
【问题讨论】:
标签: pandas string-matching sql-like
有没有办法在 pandas 文本 DataFrame 列上执行类似于 SQL's LIKE syntax 的操作,以便返回索引列表或可用于索引数据帧的布尔值列表?例如,我希望能够匹配列以 'prefix_' 开头的所有行,类似于 SQL 中的WHERE <col> LIKE prefix_%。
【问题讨论】:
标签: pandas string-matching sql-like
您可以使用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
【讨论】:
s.str.startswith('a', na=False) 强制他们返回 False。
你可以使用
s.str.contains('a', case = False)
【讨论】:
SQL - WHERE column_name LIKE 's%'
Python - column_name.str.startswith('s')
SQL - WHERE column_name LIKE '%s'
Python - column_name.str.endswith('s')
SQL - WHERE column_name LIKE '%s%'
Python - column_name.str.contains('s')
更多选项,请查看:https://pandas.pydata.org/pandas-docs/stable/reference/series.html
【讨论】: