高效的自定义Regex查询。

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

所以,我有一个简单的疑问,但我是一个新的regex。我正在使用一个Pandas DataFrame。其中一列包含了姓名,但有些姓名写得像 "John Doe",有些则写得像 "John.Doe"。然而,有些名字写成 "John Doe",但有些名字写成 "John.Doe",我需要把所有的名字都写成 "John Doe"。我需要在整个数据框上运行这个。什么是regex查询来解决这个问题,并以一种有效的方式。Col Name = 'Customer_Name'。如果需要更多细节,请告诉我。

python regex pandas split data-cleaning
1个回答
2
投票

如果这是唯一的条件,请试着执行这个命令,用空格代替所有的.。

df['Customer_Name'] = df['Customer_Name'].str.replace('.', ' ')

1
投票

你所需要的只是使用 apply 函数,它将一个函数应用于列上的所有值。你不需要用regex来实现,但是下面的例子中包含了这两个功能。

import pandas as pd
import re

# Read CSV File
df = pd.read_csv(<PATH TO CSV FILE>)

# Apply Function to Column
df['NewCustomerName'] = df['Customer_Name'].apply(format_name)

# Function that does replacement
def format_name(val):
  return val.replace('.', ' ')
  # return re.sub('\.', ' ', val) # If you would like to use regex
© www.soinside.com 2019 - 2024. All rights reserved.