Reputation: 79
I would like to map the following values in a text column in a DataFrame like this:
To this:
I thought I could use a dictionary to map the text snippets to the single words. Here is my code that I've tried:
import pandas as pd
data = {"col": ['i am hungry, you are pretty', 'i am hungry, you are pretty, i love flowers',
'i am hungry, i love flowers', 'i am hungry,choccies are nice']}
replace = {'hungry': 'i am hungry',
'pretty': 'you are pretty',
'flowers': 'i love flowers',
'choccies':'choccies are nice'}
new = df.replace({"col": replace})
But I just get the original DataFrame back.
Upvotes: 0
Views: 87
Reputation: 114
You need to switch the keys and the values of the dictionary, since replace method requires the dictionary to be in the form {"what to replace" : "replacement"}. You also need to specify the parameter regex as true, so that the replacement is carried out as a regex filtering. This should do it.
replace = { 'i am hungry' : 'hungry',
'you are pretty' : 'pretty',
'i love flowers' : 'flowers',
'choccies are nice': 'choccies' }
df = df.replace({'col': replace}, regex = True)
Upvotes: 0