1

I am trying to map a specific value from pandas to an existing dictionary and then add that value to my data frame.

x = {'apples':1, "pears":45, 'grapes':7777}

f = df.fruit

>>>f

0    apples                            
1    grapes                             

I would like to map df.fruit to dictionary x.

I am trying this:

df['amount'] = df['fruit'].map(x)

I am getting NaN values when I try this. What am I doing wrong here. I thought map was the correct way of doing this but now I am not sure.

2
  • 3
    It works fine? imgur.com/a/wHaYI Commented Apr 21, 2017 at 20:56
  • 2
    Maybe there is white-space around your strings? try df.fruit.str.strip().map(x) Commented Apr 21, 2017 at 21:02

2 Answers 2

1

This works fine:

import pandas as pd
x = {'apples':1, "pears":45, 'grapes':7777}
df = pd.DataFrame({'fruit':['apples','grapes']})
df['amount'] = df['fruit'].map(x)

Then df is:

    fruit   amount
0   apples  1
1   grapes  7777
Sign up to request clarification or add additional context in comments.

Comments

0
df['amount']=df['fruit'].apply(lambda y:x[y])

2 Comments

please explain the problem in OP's code and how your solution solve it.
they are pretty much the same, but this one would throw an error the dictionary doesn't have the key you're trying to map. You might need to use .get to set a default value, like nan as the .map behavior, or return the same entry as of the dataframe, or any default value you want ...

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.