0

I have a df

df = pd.DataFrame(data={'A': [1,2,3,4,5,6,7,8],
                       'B': [10,20,30,40,50,60,70,80]})
    A   B
0   1   10
1   2   20
2   3   30
3   4   40
4   5   50
5   6   60
6   7   70
7   8   80

which I selected a few rows from. Then I have a dictionary containig values that I should insert in B column if key matches with value in A column of df

my_dict = {2: 39622884,
           4: 82709546,
           5: 28166511,
           7: 89465652}

When I use the following assignment

df.loc[df['A'].isin(my_dict.keys())]['B'] = list(my_dict.values())

I get the error: ValueError: Length of values does not match length of index

The desirable output is

    A   B
0   1   10
1   2   39622884
2   3   30
3   4   82709546
4   5   50
5   6   28166511
6   7   89465652
7   8   80

What is the correct way to implement this procedure?

1
  • @QuangHoang solution is the way I would have done it. But, I think this fixes your problem. df.loc[df['A'].isin(my_dict.keys()), 'B'] = list(my_dict.values()) Commented Feb 18, 2020 at 15:48

1 Answer 1

3

You can make do with map and fillna:

df['B'] = df['A'].map(my_dict).fillna(df['B'])

Output:

   A           B
0  1        10.0
1  2  39622884.0
2  3        30.0
3  4  82709546.0
4  5  28166511.0
5  6        60.0
6  7  89465652.0
7  8        80.0
Sign up to request clarification or add additional context in comments.

Comments

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.