使用正则表达式

时间:2018-06-04 00:37:15

标签: python regex pandas

我有一个包含如下字符串的数据框列:

df.column1:
0 R$ 27.467.522,00 (Vinte e sete milhões, quatro...
1 NaN
2 R$ 35.314.312,12 (Trinta e cinco milhões, trezentos...
3 R$ 1.231,34 (Mil duzentos e trinta e um reais e...

我只想得到数字,不管小数,所以它看起来像这样:

df.column1:
0 27467522
1 NaN
2 35314312
3 1231

我试图用正则表达式做到这一点:

df['column1']=df['column1'].str.extract('[REGEX CODE]')

但是,我没有使用正则表达式。我试过像这样的解决方案:

df['column1']=df['column1'].str.extract('(.*?,)').str.extract('(\d+)')
df['column1']=df['column1'].str.extract('(\s*,.*)').str.extract('(\d+)')

但我还没有能够做对。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

使用 str.replace ,然后 str.extract

df.column1.str.replace('.', '').str.extract(r'(\d+)')

          0
0  27467522
1       NaN
2  35314312
3      1231

这里用逗号表示小数,因此通过替换句点并使用提取来查找第一个匹配,数字将匹配,忽略小数。