【问题标题】:Pandas Dataframe str split maxPandas Dataframe str split max
【发布时间】:2020-01-16 17:32:51
【问题描述】:

我有一个数据框,其中有一列包含个人姓名。名称并不总是采用相同的格式,因此我试图将名字和姓氏分成单独的列。例如,我可能会看到:

Smith John

Smith, John

Smith, John A

Smith John A

Smith John and Jane

一致的模式是姓氏在前。如何为姓氏创建两个单独的字段,然后是第二列,它不是姓氏。这是我到目前为止所拥有的

owners_df['normal_name'] = owners_df['name'].str.replace(', ', ' ')
owners_df['lastname'] = owners_df["normal_name"].str.split(' ', 1)[0]
owners_df['firstname'] = owners_df["normal_name"].str.split(' ', 1)[1]

问题是我收到一个错误“ValueError:值的长度与索引的长度不匹配”

【问题讨论】:

  • 当您运行此owners_df["normal_name"].str.split(' ', 1)[0] 时,您只抓取了第一行,您是否能够生成minimal reproducible example 并发布您的预期输出?

标签: python pandas split


【解决方案1】:

正如@Datanovice 在评论中所说的“当你运行这个owners_df["normal_name"].str.split(' ', 1)[0] 时,你只抓取了第一行”

使用.str 访问器获得预期输出

owners_df['lastname'] = owners_df["normal_name"].str.split(' ', n=1).str[0]
owners_df['firstname'] = owners_df["normal_name"].str.split(' ', n=1).str[1]

See docs 注意n 参数将拆分限制为一次。

【讨论】:

  • See docs 请注意n 参数以将拆分限制为一次。请将此文本添加到您的解决方案中。
【解决方案2】:

分手后您正在寻找.str[0].str[1:]

ser=pd.Series(['Smith John',
'Smith John',
'Smith John A',
'Smith John A',
'Smith John and Jane'])

ser.str.split(' ').str[0]

0    Smith
1    Smith
2    Smith
3    Smith
4    Smith

#leaving off the .str.join will give a list, which may be preferable in some use cases
ser.str.split(' ').str[1:].str.join(' ') 

0             John
1             John
2           John A
3           John A
4    John and Jane

如果您只想将每个元素移动到单独的列中,则可以传递 expand=True

ser.str.split(' ', expand=True)

    0       1       2       3
0   Smith   John    None    None
1   Smith   John    None    None
2   Smith   John    A       None
3   Smith   John    A       None
4   Smith   John    and     Jane

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 2018-08-29
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多