4

Here is an example, where column is assigned when the row is a dictionary key: https://stackoverflow.com/a/20250996/12603542

What I am looking for is case, where column is assigned when the row contains a dictionary key.

For example (based on example above):

import pandas as pd
df = pd.DataFrame({'col1': {0: 'aba', 1: 'abc', 2: 'abx'}})

#gives me a DataFrame
     col1 
0    aba #contains 'ba'
1    abc #will NOT be replaced
2    abx #contains 'bx'

dictionary = {'ba': 5, 'bx': 8}

#and I need to get:

     col1 
0    5
1    abc
2    8
bakunet
  • 559
  • 8
  • 25

1 Answers1

5

You could use DataFrame.replace with regex parameter set to True and pass the mapping dictionary.

df.replace(dictionary, regex=True)

#   col2
# 0    5
# 1  abc
# 2    8

This usage of df.replace is less known. You can read more about it here.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58