2

I have the below dataframe:

enter image description here

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..

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! It is completing the task, but returning this warning: C:\Users\User\Documents\Anaconda\lib\site-packages\ipykernel_launcher.py:5: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy """. Do you know what this means?
@Dean - it means DataFrame is created by some filter, need .copy() like this
Okay, so you make a copy of the dataframe you have filtered instead of changing the original one, per se?
@Dean - exactly, you need modify your code before mapping similar way - if still problem, please show me code used before map and I can help you find where is necessary add .copy()
No, that's perfect. Thanks for explaining. I am still very new to python so most important for me is to get the understanding :) the df was a 'filtered' version of the original dataframe as only need the 3 columns from original 10+. So .copy() works great - thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.