I have a dataframe with multiple columns. One of the columns, ‘TName’, has a different track names. I would like to create a new column for my dataframe which has the country of each racetrack.
My code (idk what to do with the last two lines):
austracks = ['Ascot', 'Balnarring']
nztracks = ['Te Aura']
hktracks = ['Sha Tin']
singtracks = ['Singapore']
df['Country'] = df['TName']
(["AUS" for c in austracks] + ["NZ" for c in nztracks] + ["HK" for c in nztracks] + ["SING" for c in nztracks])
Desired dataframe:
TName Country
Ascot AUS
Balnarring AUS
Te Aura NZ
>Solution :
Use Series.map if need for each list assign only one country:
austracks = ['Ascot', 'Balnarring']
nztracks = ['Te Aura']
d = {**dict.fromkeys(austracks,'AUS'), **dict.fromkeys(nztracks,'NZ')}
df['Country'] = df['TName'].map(d)
print (df)
TName Country
0 Ascot AUS
1 Balnarring AUS
2 Te Aura NZ