【问题标题】:Split one column into multiple columns by multiple delimiters in Pandas在 Pandas 中通过多个分隔符将一列拆分为多列
【发布时间】:2021-03-05 06:51:19
【问题描述】:

给定一个数据框如下:

                                     player     score
0   Sergio Agüero Forward — Manchester City    209.98
1            Eden Hazard Midfield — Chelsea    274.04
2          Alexis Sánchez Forward — Arsenal    223.86
3     Yaya Touré Midfield — Manchester City    197.91
4  Angel María Midfield — Manchester United    132.23

如何将player 拆分为三个新列namepositionteam

                                     player     score   name    position  team
0   Sergio Agüero Forward — Manchester City    209.98   Sergio  Forward   Manchester City
1            Eden Hazard Midfield — Chelsea    274.04   Eden    Midfield  Chelsea
2          Alexis Sánchez Forward — Arsenal    223.86   Alexis  Forward   Arsenal
3     Yaya Touré Midfield — Manchester City    197.91   Yaya    Midfield  Manchester City
4  Angel María Midfield — Manchester United    132.23   Angel   Midfield  Manchester United

我考虑用df[['name_position', 'team']] = df['player'].str.split(pat= ' — ', expand=True) 将其拆分为两列,然后将name_position 拆分为nameposition。但是有没有更好的解决方案?

非常感谢。

【问题讨论】:

  • 我认为您的解决方案很好。

标签: python-3.x pandas dataframe


【解决方案1】:

您可以使用string.split() 按空格分割python 字符串。这会将您的文本分解为'words',然后您可以简单地访问您喜欢的文本,如下所示:

string =  "Sergio Agüero Forward — Manchester City"
name = string.split()[0]
position = string.split()[2]
team = string.split()[4] + (string.split().has_key(5) ? string.split()[5] : '')

对于更复杂的模式,您可以使用正则表达式,这是一个强大的字符串模式查找工具。

希望这有帮助:)

【讨论】:

    【解决方案2】:

    如果您想一次性完成,也可以使用str.extract

    print(df["player"].str.extract(r"(?P<name>.*?)\s.*?\s(?P<position>[A-Za-z]+)\s—\s(?P<team>.*)"))
    
         name  position               team
    0  Sergio   Forward    Manchester City
    1    Eden  Midfield            Chelsea
    2  Alexis   Forward            Arsenal
    3    Yaya  Midfield    Manchester City
    4   Angel  Midfield  Manchester United
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 2021-12-10
      • 1970-01-01
      • 2019-09-23
      • 2019-05-11
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多