在 pandas 数据框替换功能中使用正则表达式匹配的组 [英] Using regex matched groups in pandas dataframe replace function

查看:94
本文介绍了在 pandas 数据框替换功能中使用正则表达式匹配的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习python/pandas,并且喜欢它的强大和简洁.

I'm just learning python/pandas and like how powerful and concise it is.

在数据清理过程中,我想在带有正则表达式的数据框中的列上使用replace,但是我想重新插入部分匹配项(组).

During data cleaning I want to use replace on a column in a dataframe with regex but I want to reinsert parts of the match (groups).

简单示例: 姓氏,名字->姓氏

Simple Example: lastname, firstname -> firstname lastname

我尝试了以下类似操作(实际情况比较复杂,请原谅简单的正则表达式):

I tried something like the following (actual case is more complex so excuse the simple regex):

df['Col1'].replace({'([A-Za-z])+, ([A-Za-z]+)' : '\2 \1'}, inplace=True, regex=True)

但是,这将导致空值.匹配部分按预期工作,但值部分不起作用. 我想这可以通过拆分和合并来实现,但是我正在寻找有关正则表达式组是否可以用于替换的一般答案.

However, this results in empty values. The match part works as expected, but the value part doesn't. I guess this could be achieved by some splitting and merging, but I am looking for a general answer as to whether the regex group can be used in replace.

推荐答案

我认为您的RegEx遇到了一些问题.

I think you have a few issues with the RegEx's.

@Abdou刚刚说过使用'\\2 \\1'或更好的r'\2 \1',因为'\1'是具有ASCII码1

As @Abdou just said use either '\\2 \\1' or better r'\2 \1', as '\1' is a symbol with ASCII code 1

如果您使用正确的RegEx,则您的解决方案应该可以工作:

Your solution should work if you will use correct RegEx's:

In [193]: df
Out[193]:
              name
0        John, Doe
1  Max, Mustermann

In [194]: df.name.replace({r'(\w+),\s+(\w+)' : r'\2 \1'}, regex=True)
Out[194]:
0          Doe John
1    Mustermann Max
Name: name, dtype: object

In [195]: df.name.replace({r'(\w+),\s+(\w+)' : r'\2 \1', 'Max':'Fritz'}, regex=True)
Out[195]:
0            Doe John
1    Mustermann Fritz
Name: name, dtype: object

这篇关于在 pandas 数据框替换功能中使用正则表达式匹配的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆