使用正则表达式在 Pandas 数据框中字符串开头的大括号内去除数字

Posted

技术标签:

【中文标题】使用正则表达式在 Pandas 数据框中字符串开头的大括号内去除数字【英文标题】:Using regex to strip numbers inside curly braces at the start of the string in a Pandas dataframe 【发布时间】:2021-02-11 20:07:46 【问题描述】:

我有一列熊猫数据框 (df)。它看起来像这样:

Mese
__________
12313Luglio
34Maggio

我试图使用正则表达式来摆脱 以及介于两者之间的所有内容:

df['Mese']=[re.sub(r'^d+','', str(x)) for x in df['Mese']]

它不起作用。有什么帮助吗?

【问题讨论】:

【参考方案1】:

您需要使用Series.str.replace^\\d+ 模式:

 df['Mese'] = df['Mese'].str.replace(r'^\\d+', '')

熊猫测试:

>>> import pandas as pd
>>> df = pd.DataFrame('Mese':['12313Luglio','34Maggio'])
>>> df['Mese'] = df['Mese'].str.replace(r'^\\d+', '')
>>> df
     Mese
0  Luglio
1  Maggio

^\\d+pattern matches 是字符串开头大括号内的数字。

【讨论】:

以上是关于使用正则表达式在 Pandas 数据框中字符串开头的大括号内去除数字的主要内容,如果未能解决你的问题,请参考以下文章