繁体   English   中英

如何在Pandas数据框中使用正则表达式拆分名称?

[英]How to split names using regular expression in Pandas dataframe?

我的数据集如下所示。 我正在尝试使用正则表达式将“第二”列分为标题,名和姓。我是python和regex的新手。

到目前为止,我的代码如下所示

def spilt_it(name):
re.findall()
if x :
return(x.group())

资料集:

{
    'Name': {0: ' Braund', 1: ' Heikkinen', 2: ' Allen', 3: ' Moran', 4: ' McCarthy'}, 
    'Fullname': {0: ' Mr. Owen Harris ', 1: ' Miss. Laina ', 2: ' Mr. William Henry ', 3: ' Mr. James ', 4: ' Mr. Timothy J '}, 
    'num': {0: 1, 1: 0, 2: 0, 3: 0, 4: 0}
}

使用pandas.Series.str.split你可以分割你的Fullname由空格字符列" "n=-1表示返回所有splited字。 因此,使用df["Fullname"].str.split(" ", n = -1, expand = True)完整工作示例,

import pandas as pd
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
df = pd.DataFrame({'Name': {0: ' Braund', 1: ' Heikkinen', 2: ' Allen', 3: ' Moran', 4: ' McCarthy'}, 'Fullname': {0: ' Mr. Owen Harris ', 1: ' Miss. Laina ', 2: ' Mr. William Henry ', 3: ' Mr. James ', 4: ' Mr. Timothy J '}, 'num': {0: 1, 1: 0, 2: 0, 3: 0, 4: 0}})

new = df["Fullname"].str.split(" ", n = -1, expand = True) 
# making seperate title column from new data frame 
df["Title"]= new[1]   
# making seperate first name column from new data frame 
df["First Name"]= new[2] 
# making seperate last name column from new data frame
df["Last Name"]= new[3]
print(df.head())

输出:

         Name             Fullname  num  Title First Name Last Name
0      Braund     Mr. Owen Harris     1    Mr.       Owen    Harris
1   Heikkinen         Miss. Laina     0  Miss.      Laina
2       Allen   Mr. William Henry     0    Mr.    William     Henry
3       Moran           Mr. James     0    Mr.      James
4    McCarthy       Mr. Timothy J     0    Mr.    Timothy         J

要点:使用函数str.split(' ', n=1, expand=True)

我在您的示例中没有看到任何姓氏,所以我只作一个拆分。 您可以使用参数n = 1或n = 2等使任意多。

首先:从名称中删除一些多余的空格,然后在第一个空格处拆分名称:

df = pd.DataFrame(data)

split_names = (df['Fullname']
    .str.strip()
    .str.split(' ', n=1, expand=True)
    .rename(columns={0:'Title', 1:'First_name'})
)

然后:使用pd.concat()将此拆分名称添加到您的数据框中

df = pd.concat([df, split_names], axis=1)

结果:

print(df)
         Name             Fullname  num  Title     First_name
0      Braund     Mr. Owen Harris     1    Mr.    Owen Harris
1   Heikkinen         Miss. Laina     0  Miss.          Laina
2       Allen   Mr. William Henry     0    Mr.  William Henry
3       Moran           Mr. James     0    Mr.          James
4    McCarthy       Mr. Timothy J     0    Mr.      Timothy J

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM