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

Pandas Python – Add values to new column from a dict with keys matching the index of a dataframe

I have a dictionary that for examples sake, looks like

{‘a’: 1, ‘b’: 4, ‘c’: 7}

I have a dataframe that has the same index values as the keys in this dict.

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

I want to add each value from the dict to the dataframe.

I feel like doing a check for every row of the DF, checking the index value, matching it to the one in the dict, then trying to add it is going to be a very slow way right?

Could anyone point me in the right direction? I’ve been struggling with Pandas.

Thanks

>Solution :

You can use map and assign back to a new column:

d = {'a': 1, 'b': 4, 'c': 7}
df = pd.DataFrame({'c':[1,2,3]},index=['a','b','c'])

df['new_col'] = df.index.map(d)

prints:

   c  new_col
a  1        1
b  2        4
c  3        7
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