Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Pandas DataFrame column values based on containing dictionary keys

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
like image 593
bakunet Avatar asked Oct 24 '25 17:10

bakunet


1 Answers

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.

like image 56
Ch3steR Avatar answered Oct 27 '25 07:10

Ch3steR