使用
map
和
dictionary
-首先用关键字中的新名称和值中的列表创建dict,然后在dict理解中相互交换到平面字典:
d = {'short':short,
'intermediate':inter,
'long':long,
'plate':plate,
'road':road}
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}
df['Type'] = df['Race'].map(d1)
print (df)
Race Start Mid Race Total Laps DRIVER RATING Type
0 1 5 23 207 105.2 plate
1 2 16 7 325 94.2 intermediate
2 3 10 2 267 106.1 intermediate
3 4 5 11 311 80.0 short
4 5 6 3 200 113.0 long
如果希望前4个类别中的所有值都不匹配,请设置为
road
去除
路
从第一个字典添加
fillna
对于重新计算所有不匹配的值:
d = {'short':short,
'intermediate':inter,
'long':long,
'plate':plate}
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}
df['Type'] = df['Race'].map(d1).fillna('road')
细节
:
print (d1)
{
4: 'short', 6: 'short',
8: 'short', 9: 'short',
11: 'short', 20: 'short',
24: 'short', 28: 'short',
30: 'short', 33: 'short',
35: 'short', 2: 'intermediate',
3: 'intermediate', 7: 'intermediate',
12: 'intermediate', 13: 'intermediate',
17: 'intermediate', 19: 'intermediate',
25: 'intermediate', 27: 'intermediate',
32: 'intermediate', 34: 'intermediate',
36: 'intermediate', 5: 'long',
14: 'long', 15: 'long',
21: 'long', 23: 'long',
26: 'long', 1: 'plate',
10: 'plate', 18: 'plate',
31: 'plate', 16: 'road',
22: 'road', 29: 'road'
}