我有一些足球数据,其中包含两个球队名称和一些数字数据:
ar = [
["browns", "patriots", 2, 5],
["patriots", "bills", 4, 15],
["browns", "bills", 1, 10],
["eagles", "browns", 3, 11]
]
frame = pandas.DataFrame(ar, columns=['Team1', 'Team2', 'Down', 'ToGo'])
Run Code Online (Sandbox Code Playgroud)
我想将团队名称转换为枚举类型,我可以对第一个团队名称执行此操作,例如:
frame['Team1'], uniques = frame['Team1'].factorize()
Run Code Online (Sandbox Code Playgroud)
我怎样才能同时对两个团队名称执行此操作,以便具有一致的唯一性并且没有缺失值?请注意,这'bills'
不在Team1
列中,所以我不能只应用映射(尽管我也不知道如何做到这一点)。
编辑:生成的团队名称应如下所示:
Team1 Team2
0 0 1
1 1 3
2 0 3
3 2 0
Run Code Online (Sandbox Code Playgroud)
因此“browns”始终标记为“0”,在第 0 行中标记为 Team1,在第 3 行中标记为 Team2。
import numpy as np
# get the unique values from the two columns
unique = np.unique(df[['Team1', 'Team2']])
# get the factors
factors = np.arange(len(unique))
# map the values to the corresponding factor
df[['Team1', 'Team2']] = df[['Team1', 'Team2']].replace(unique, factors)
>>> df
Team1 Team2 Down ToGo
0 1 3 2 5
1 3 0 4 15
2 1 0 1 10
3 2 1 3 11
Run Code Online (Sandbox Code Playgroud)