如何将足球联赛数据集的Game列拆分为三列?求单行实现方案
Great question! Your current approach works, but splitting the Game column twice is redundant—we can make this more efficient by splitting once and reusing the result. Let's break down the better options:
Option 1: Two efficient lines (no redundant splits)
Since you're already splitting into team_1 and team_2, you don't need to split again to get the home column. Just reference the existing column (note: there's a slight contradiction between your description and code—we'll cover both cases):
# If your code's logic is correct (home team is the second value after @) df[['team_1', 'team_2']] = df.Game.str.split(' @', expand=True) df['home'] = df['team_2'] # If your description is accurate (home team is the value before @) df[['team_1', 'team_2']] = df.Game.str.split(' @', expand=True) df['home'] = df['team_1']
Option 2: Single-line solution using assign
If you prefer a one-liner, you can chain the split and column assignment together with pandas.DataFrame.assign:
# For home team as team_2 (matches your code) df = df.assign(**df.Game.str.split(' @', expand=True).rename(columns={0: 'team_1', 1: 'team_2'})).assign(home=lambda x: x['team_2']) # For home team as team_1 (matches your description) df = df.assign(**df.Game.str.split(' @', expand=True).rename(columns={0: 'team_1', 1: 'team_2'})).assign(home=lambda x: x['team_1'])
This splits the column once, renames the split results, then adds the home column without reprocessing the original string.
Bonus: Explicit pattern matching with str.extract
Another clean approach uses regular expressions to explicitly capture the two teams, making the string format clear:
df[['team_1', 'team_2']] = df.Game.str.extract(r'(.*)\s@(.*)', expand=True) df['home'] = df['team_2'] # or df['team_1'] based on your actual home team definition
The regex (.*)\s@(.*) grabs everything before the spaced @ as team_1 and everything after as team_2.
All these methods avoid redundant string processing, which is especially helpful for large datasets.
内容的提问来源于stack exchange,提问作者Roy

