151

I would like to add a column 'D' to a dataframe like this:

U,L
111,en
112,en
112,es
113,es
113,ja
113,zh
114,es

based on the following Dictionary:

d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'}

so that the resulting dataframe appears as:

U,L,D
111,en,en
112,en,en
112,es,en
113,es,es
113,ja,es
113,zh,es
114,es,es

So far I tried the pd.join() method but I can't figured out how it works with Dictionaries.

Fabio Lamanna
  • 20,504
  • 24
  • 90
  • 122
  • 6
    This is another example of a question erroneously marked as a duplicate. As a reminder to all users: Just because two questions have the same answers, does not mean they are duplicates. This question should be re-opened. StackOverflow should be a key→value store from problems to solutions. If a question can be solved using an answer from an unrelated problem, please provide that as a new answer, adapted to the specific problem the user is facing, rather than marking the question as duplicate. – MRule Feb 05 '23 at 16:38

3 Answers3

275

Call map and pass the dict, this will perform a lookup and return the associated value for that key:

In [248]:

d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'}
df['D'] = df['U'].map(d)
df
Out[248]:
     U   L   D
0  111  en  en
1  112  en  en
2  112  es  en
3  113  es  es
4  113  ja  es
5  113  zh  es
6  114  es  es
EdChum
  • 376,765
  • 198
  • 813
  • 562
60

Here is a simpler way that should work well too:

df["D"] = pd.Series(d)

Note: The dict keys need to be in the DataFrame index for this.

Sawant
  • 4,321
  • 1
  • 27
  • 30
8

I got TypeError: 'dict' object is not callable error for EdChum's solution when I try to use index.map()... And I haven't found a way to get index as Series.

So I found another solution to this problem by creating a Series object from the dict object first.

new_d = pd.Series(d)

And then do the pd.join with the column you like. That may help.

Yuan Tao
  • 447
  • 5
  • 7