Pandas 文本匹配就像 SQL 的 LIKE 吗?

问题描述 投票:0回答:3

有没有办法在 pandas text DataFrame 列上执行类似于 SQL 的 LIKE 语法 的操作,以便它返回索引列表或可用于索引数据帧的布尔值列表?例如,我希望能够匹配列以“prefix_”开头的所有行,类似于 SQL 中的

WHERE <col> LIKE prefix_%

pandas string-matching sql-like
3个回答
49
投票

您可以使用 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
...

另请参阅文档的 SQL 比较部分。

注意:(正如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

14
投票
  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


10
投票

你可以使用

s.str.contains('a', case = False)
© www.soinside.com 2019 - 2024. All rights reserved.