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

2024-09-28 21:57:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据集如下所示。我尝试使用正则表达式将“第二”列拆分为title、First name和last name。在

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

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

数据集:

^{pr2}$

Tags: 数据代码namerereturniftitledef
2条回答

使用pandas.Series.str.split可以按空格字符" "拆分Fullname列,n=-1表示返回所有拆分的单词。所以,使用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())

输出:

^{pr2}$

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

我在你的例子中没有看到姓,所以我只做了一个分割。您可以使用参数n=1或n=2等来生成任意多个

首先:strip从你的名字中多出一些空格,然后split名字在第一个空格上:

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()将此拆分名称添加到数据帧:

^{pr2}$

结果:

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

相关问题 更多 >