Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create column based on existing column in dataframe and lists

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading