1

The Title is somewhat inelegant, but I'm not sure how to better phrase it. Anyway, say I have a dataframe with two columns:

Name    ZIP

Abe     22222
Beth    11111
Charlie 11111
David   22222

And I also have a dictionary:

categ_dict = {
    11111 : "Local",
    22222 : "Guest"
            }

I want to create a third column - Category - and populate it by comparing the content of each cell in the ZIP column against the the key-value pairs in the dictionary. If the content of that cell matches the key of a given pair, the "Category" cell in the same row is populated with the value of that pair. At the end, it should look like:

Name    ZIP     Category

Abe     22222   Guest
Beth    11111   Local
Charlie 11111   Local
David   22222   Guest

Any insight would be greatly appreciated.

Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
  • 5
    `df['Category'] = df.ZIP.map(categ_dict)` or `df['Category'] = df.ZIP.replace(categ_dict)` – sacuL Dec 17 '18 at 20:25
  • 1
    Another alternative - `df['Category'] = df['ZIP'].apply(lambda val:categ_dict.get(val,replace with any default value))` – Venkata Gogu Dec 17 '18 at 20:32
  • @sacul Wow, both fast and effective! They both work. Do you want to post it as answer so I can mark it answered? – Jack Fleeting Dec 17 '18 at 20:33
  • @JackFleeting, glad it helped! The duplicate takes care of it, though, I don't think it needs an answer posted (this post can act as a way to re-direct future users to the answer) :) – sacuL Dec 17 '18 at 20:34
  • 1
    @sacul You're right - I guess that since the previous question was phrased as a mapping of a column against column, not column against a dictionary, it didn't come up in my search. – Jack Fleeting Dec 17 '18 at 20:41
  • 1
    @Venkata Gogu - Thanks, your alternative works as well. – Jack Fleeting Dec 17 '18 at 20:43
  • @JackFleeting Glad it helped you – Venkata Gogu Dec 17 '18 at 20:45

0 Answers0