ZeroStack
ZeroStack

Reputation: 1109

Replace pandas column values using a key on another column and value from a dictionary

I have searched stackoverflow and gone over a few questions which are related to this, i.e

Remap values in pandas column with a dict

The key distinction is these questions answer how to replace column values with a key on the same column and a value from a dictionary.

For example:

import pandas as pd

df = pd.DataFrame({'key': ['bacd', 'fdvdf', 'scsdc'],
                   'value': [1, 2, 4]})

df['key'].replace({'bacd' : 200, 'sdfvs': 5000}, inplace=True)

    key   value
0   200     1
1   fdvdf   2
2   scsdc   4

I am trying to use the key in a dictionary to identify the row, but update a different column (value in this case) instead of the key column.

Desired output:

    key     value
0   bacd    200
1   fdvdf   2
2   scsdc   4

Thanks in advance.

Upvotes: 0

Views: 2076

Answers (1)

user3483203
user3483203

Reputation: 51165

Using map with fillna

dct = {'bacd': 200, 'sdfvs': 5000}

df.assign(value=df.key.map(dct).fillna(df.value))

     key  value
0   bacd  200.0
1  fdvdf    2.0
2  scsdc    4.0

Upvotes: 2

Related Questions