简体   繁体   中英

Add column to pandas.Dataframe using key values from dictionary

I have the below dataframe:

在此处输入图像描述

And I have the below dictionary:

resource_ids_dict = {'Austria':1586023272, 'Bulgaria':1550004006, 'Croatia':1131119835, 'Denmark':1703440195, 
                     'Finland':2005848983, 'France':1264698819, 'Germany':1907737079, 'Greece':2113941104, 
                     'Italy':27898245, 'Netherlands':1832579427, 'Norway':1054291604, 'Poland':1188865122, 
                     'Romania':270819662, 'Russia':2132391298, 'Serbia':1155274960, 'South Africa':635838568, 
                     'Spain':52600180, 'Switzerland':842323896, 'Turkey':1716131192, 'UK':199152257}

I am using the above dictionary values to make calls to a vendor API. I then append all the return data into a dataframe df .

What I would like to do now is add a column after ID that is the dictionary keys of the dictionay values that lie in ResourceSetID .

I have had a look on the web, but haven't managed to find anything (probably due to my lack of accurate key word searches). Surely this should be a one-liner? I want avoid looping through the dataframe and the dictionary and mapping that way..

Use Series.map but first is necessary swap values with keys in dictionary:

d = {v:k for k, v in resource_ids_dict.items()}
#alternative
#d = dict(zip(resource_ids_dict.values(), resource_ids_dict.keys()))
df['new'] = df['ResourceSetID'].map(d)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM