有没有办法在 pandas text DataFrame 列上执行类似于 SQL 的 LIKE 语法 的操作,以便它返回索引列表或可用于索引数据帧的布尔值列表?例如,我希望能够匹配列以“prefix_”开头的所有行,类似于 SQL 中的
WHERE <col> LIKE prefix_%
。
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
...
注意:(正如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
SQL -
WHERE column_name LIKE 's%'
column_name.str.startswith('s')
SQL -
WHERE column_name LIKE '%s'
column_name.str.endswith('s')
SQL -
WHERE column_name LIKE '%s%'
column_name.str.contains('s')
有关更多选项,请检查:https://pandas.pydata.org/pandas-docs/stable/reference/series.html
你可以使用
s.str.contains('a', case = False)