【问题标题】:Custom Regex Query in an effiicient manner以有效的方式自定义正则表达式查询
【发布时间】:2020-10-05 07:41:01
【问题描述】:
所以,我有一个简单的疑问,但我是正则表达式的新手。我正在使用 Pandas DataFrame。其中一列包含名称。但是,有些名字写成“John Doe”,但有些名字写成“John.Doe”,我需要把它们都写成“John Doe”。我需要在整个数据帧上运行它。什么是正则表达式查询以有效地解决此问题。列名称 = 'Customer_Name'。让我知道是否需要更多详细信息。
【问题讨论】:
标签:
python
regex
pandas
split
data-cleaning
【解决方案1】:
尝试运行它来替换所有 .有空间,如果这是你唯一的条件:
df['Customer_Name'] = df['Customer_Name'].str.replace('.', ' ')
【解决方案2】:
您只需要使用 pandas 中的 apply 函数,该函数将函数应用于列上的所有值。您不需要正则表达式,但下面是一个同时具有这两个示例的示例
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