将足球比分转换为 Python 中的数字

Converting football score to a number in Python

我是 Python 的新手,我正在尝试对足球比分数据框进行一些计算。 有没有办法将足球比分(例如 3-2、2-0..)从对象 dtype 转换为数字,以便我可以对它们执行一些数值运算?

提前致谢。

将来,提供具有预期输入和输出的示例数据集。

您可以拆分 '-' 字符上的列。将列转换为 int 并执行 groupby 以求总分。

给定:

print(df)
  Team Result Score
0    A      W   3-0
1    A      W   3-2
2    A      L   2-4
3    A      L   1-2
4    B      W   1-0
5    B      L   0-1
6    B      T   1-1
7    B      L   2-3

代码:

import pandas as pd


df = pd.DataFrame([['A','W','3-0'],
                   ['A','W','3-2'],
                   ['A','L','2-4'],
                   ['A','L','1-2'],
                   ['B','W','1-0'],
                   ['B','L','0-1'],
                   ['B','T','1-1'],
                   ['B','L','2-3']], columns=['Team','Result','Score'])

df[['Team Points','Opp Points']] = df['Score'].str.split('-',expand=True)
df[['Team Points','Opp Points']] = df[['Team Points','Opp Points']].astype(int)

df_sum = df.groupby(['Team'])['Team Points'].sum()

输出:

print(df)
  Team Result Score  Team Points  Opp Points
0    A      W   3-0            3           0
1    A      W   3-2            3           2
2    A      L   2-4            2           4
3    A      L   1-2            1           2
4    B      W   1-0            1           0
5    B      L   0-1            0           1
6    B      T   1-1            1           1
7    B      L   2-3            2           3

总和:

print(df_sum)
Team
A    9
B    4
Name: Team Points, dtype: int32