如何分割Pandas字符串以提取中间名?

2024-05-14 01:19:15 发布

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

我想把个人的名字分成多个字符串。我能够很容易地提取名字和姓氏,但是我在提取中间名或中间名时遇到了问题,因为在每个场景中这些名称都是不同的。在

数据如下:

ID| Complete_Name               | Type
1 | JERRY, Ben                  | "I"
2 | VON HELSINKI, Olga          | "I"
3 | JENSEN, James Goodboy Dean  | "I"
4 | THE COMPANY                 | "C"
5 | CRUZ, Juan S. de la         | "I"

名字只有名字和姓氏,名字中间有两个中间名。如何从Pandas数据帧中提取中间名?我已经可以提取出名字和姓氏了。在

^{pr2}$

预期结果如下:

ID| Complete_Name               | Type | First Name | Middle Name | Last Name
1 | JERRY, Ben                  | "I"  | Ben        |             | JERRY
2 | VON HELSINKI, Olga          | "I"  | Olga       |             |
3 | JENSEN, James Goodboy Dean  | "I"  | James      | Goodboy Dean| VON HELSINKI
4 | THE COMPANY                 | "C"  |            |             |
5 | CRUZ, Juan S. de la         | "I"  | Juan       | S. de la    | CRUZ

Tags: namede名字lajuanben姓氏james
3条回答

下面是另一个使用一些简单lambda功能的答案。在

import numpy as np
import pandas as pd


""" Create data and data frame """

info_dict = {
    'ID': [1,2,3,4,5,],
    'Complete_Name':[
        'JERRY, Ben',
        'VON HELSINKI, Olga',
        'JENSEN, James Goodboy Dean',
        'THE COMPANY',
        'CRUZ, Juan S. de la',
        ],
    'Type':['I','I','I','C','I',],
    }

data = pd.DataFrame(info_dict, columns = info_dict.keys())


""" List of columns to add """
name_cols = [
    'First Name',
    'Middle Name',
    'Last Name',
    ]

"""
Use partition() to separate first and middle names into Pandas series.
Note: data[data['Type'] == 'I']['Complete_Name'] will allow us to target only the
values that we want.
"""
NO_LAST_NAMES = data[data['Type'] == 'I']['Complete_Name'].apply(lambda x: str(x).partition(',')[2].strip())
LAST_NAMES = data[data['Type'] == 'I']['Complete_Name'].apply(lambda x: str(x).partition(',')[0].strip())

# We can use index positions to quickly add columns to the dataframe.
# The partition() function will keep the delimited value in the 1 index, so we'll use
# the 0 and 2 index positions for first and middle names.
data[name_cols[0]] = NO_LAST_NAMES.str.partition(' ')[0]
data[name_cols[1]] = NO_LAST_NAMES.str.partition(' ')[2]

# Finally, we'll add our Last Names column
data[name_cols[2]] = LAST_NAMES

# Optional: We can replace all blank values with numpy.NaN values using regular expressions.
data = data.replace(r'^$', np.NaN, regex=True)

那么你应该得到这样的结果:

^{pr2}$

或者,用空白字符串替换NaN值:

data = data.replace(np.NaN, r'', regex=False)

然后你有:

   ID               Complete_Name Type First Name   Middle Name     Last Name
0   1                  JERRY, Ben    I        Ben                       JERRY
1   2          VON HELSINKI, Olga    I       Olga                VON HELSINKI
2   3  JENSEN, James Goodboy Dean    I      James  Goodboy Dean        JENSEN
3   4                 THE COMPANY    C                                       
4   5         CRUZ, Juan S. de la    I       Juan      S. de la          CRUZ

我想你可以:

# take the complete_name column and split it multiple times
df2 = (df.loc[df['Type'].eq('I'),'Complete_Name'].str
       .split(',', expand=True)
       .fillna(''))

# remove extra spaces 
for x in df2.columns:
    df2[x] = [x.strip() for x in df2[x]]

# split the name on first space and join it
df2 = pd.concat([df2[0],df2[1].str.split(' ',1, expand=True)], axis=1)
df2.columns = ['last','first','middle']

# join the data frames
df = pd.concat([df[['ID','Complete_Name']], df2], axis=1)

# rearrange columns - not necessary though
df = df[['ID','Complete_Name','first','middle','last']]

# remove none values
df = df.replace([None], '')

   ID                  Complete_Name Type  first        middle          last
0   1   JERRY, Ben                      I    Ben                       JERRY
1   2   VON HELSINKI, Olga              I   Olga                VON HELSINKI
2   3   JENSEN, James Goodboy Dean      I  James  Goodboy Dean        JENSEN
3   4   THE COMPANY                     C                                   
4   5   CRUZ, Juan S. de la             I   Juan      S. de la          CRUZ

一个str.extract调用将在这里工作:

p = r'^(?P<Last_Name>.*), (?P<First_Name>\S+)\b\s*(?P<Middle_Name>.*)' 
u = df.loc[df.Type == "I", 'Complete_Name'].str.extract(p)
pd.concat([df, u], axis=1).fillna('')

   ID               Complete_Name Type     Last_Name First_Name   Middle_Name
0   1                  JERRY, Ben    I         JERRY        Ben              
1   2          VON HELSINKI, Olga    I  VON HELSINKI       Olga              
2   3  JENSEN, James Goodboy Dean    I        JENSEN      James  Goodboy Dean
3   4                 THE COMPANY    C                                       
4   5         CRUZ, Juan S. de la    I          CRUZ       Juan      S. de la

正则表达式分解

^{pr2}$

相关问题 更多 >