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.
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?
Advertisement
Answer
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