Python/ Pandas : Search for a word in a DataFrame column and take it's value from a dictionary

Viewed 361

I have a dataframe with text column

Text
I need a new umbrella
I need new shoes

I have created a dictionary like this

dict = {'umbrella': '1','shoes':2}

I want my output dataframe to look like this

Text Value
I need a new umbrealla 1
I need new shoes 2

It should look for keys in a dictionary and populate the corresponding value against the row in a dataframe.

Can somebody suggest how to do it in python?

3 Answers

You can try series.str.extract with series.map:

df['Value'] = df['Text'].str.extract('('+'|'.join(d)+')',expand=False).map(d)

print(df)
                    Text Value
0  I need a new umbrella     1
1       I need new shoes     2

You can split the string and look up each word in the dictionary:

df['Value'] = df['Text'].str.split().apply(lambda x: [dict[i] for i in x if i in dict.keys()])

print(df)
                    Text Value
0  I need a new umbrella   [1]
1       I need new shoes   [2]

This returns a list of values for all matching words. If you just want 1 value, you can do df['Value'] = df['Value'].str[0]

Here is another way.

df['Value'] = df['Text'].replace(d,regex=True).str.extract(r'(\d)')
Related