我有以下 DF:
| Fecha | Partido | Equipo | xG | xGA |
|------------|-------------------------|---------|------|------|
| 2022-05-01 | América - Cruz Azul 0:0 | América | 1.53 | 0.45 |
| 2022-05-01 | Leon - América 2:0 | América | 1.70 | 0.35 |
我想基于 Partido 列创建三个新列,其中第一个团队转到名为 Home 的新列,第二个团队转到名为 Visitor 的列,分数转到名为 Score 的列。
期望的输出:
| Fecha | Partido | Equipo | xG | xGA | Home | Away | Score |
|------------|-------------------------|---------|------|------|-------- |------------|-------|
| 2022-05-01 | América - Cruz Azul 0:0 | América | 1.53 | 0.45 | América | Cruz Azul | 0:0 |
| 2022-05-01 | Leon - América 2:0 | América | 1.70 | 0.35 | Leon | América | 2:0 |
我曾尝试使用分隔符进行拆分,但由于某些团队的名称中有两个词,因此它不起作用。
最佳答案
使用str.extract
非常简单和一个正则表达式:
regex = r'([^-]+)\s*-\s*([^-]+) (\d+:\d+)'
df[['Home', 'Away', 'Score']] = df['Partido'].str.extract(regex)
输出:
Fecha Partido Equipo xG xGA Home Away Score
0 2022-05-01 América - Cruz Azul 0:0 América 1.53 0.45 América Cruz Azul 0:0
1 2022-05-01 Leon - América 2:0 América 1.70 0.35 Leon América 2:0
如果不想修改原来的DataFrame,也可以使用named capturing groups直接设置列名:
regex = r'(?P<Home>[^-]+)\s*-\s*(?P<Away>[^-]+) (?P<Score>\d+:\d+)'
df2 = df['Partido'].str.extract(regex)
# Home Away Score
# 0 América Cruz Azul 0:0
# 1 Leon América 2:0
# OR
df2 = df.join(df['Partido'].str.extract(regex))
# same a first output
关于Python 根据字符串条件生成新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72169421/