Daniel Arges
Daniel Arges

Reputation: 365

create new column using a dictionary key

Take this dataframe df:

df = pd.DataFrame({'col_1':['some text green', 'some text blue', 'some text dog', 'some text']})

             col_1
0  some text green
1   some text blue
2    some text dog
3        some text

And take this dictionary:

my_dict = {'color':['green', 'blue'],'animal':['dog']}

I need to create a new column new_col searching if the string contains in col_1. The strings are given in the dictionary values. If so, I need to get the dictionary key and place it in the new column. If not, just place NaN.

The result should be:

             col_1 new_col
0  some text green   color
1   some text blue   color
2    some text dog  animal
3        some text     NaN

Upvotes: 1

Views: 665

Answers (1)

bb1
bb1

Reputation: 7873

Try this:

def f(s):
    for k in my_dict:
        for v in my_dict[k]:
            if v in s:
                return k

df["new_col"] = df["col_1"].apply(f)

Upvotes: 1

Related Questions