简体   繁体   中英

How to split a column into three columns?

I have a dataset of a soccer league:

df.Game.head()

0    Man. City @Cardiff City
1     Southampton @Liverpool
2        Tottenham @Brighton
3          Chelsea @West Ham
4         Wolves @Man United

The symbol '@' before the team name indicates home team. I want to split the column into three separate columns:

  1. team_1: Team one
  2. team_2: Team two
  3. home: The home team (which has @ before the name and always comes at the second)

I have tried the following code:

df[['team_1', 'team_2']] = df.Game.str.split(' @', expand = True)

df['home'] = df.Game.str.split(' @', expand = True)[1]

Is there any better way to do that? Maybe a single-line code? Thank you!

You do not need to split twice

df[['team_1', 'team_2']] = df.Game.str.split(' @', expand = True)
df['home'] = df['team 2']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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