Skip to content
Advertisement

how do I succinctly create a new dataframe column based on matching existing column values with list of values?

I want to create a new column in a dataframe by matching the values in an existing column’s values with a predefined list of values. I have two approaches to this below. Both run but dont give me exactly what I want. I prefer the first approach over the second but not sure where I am going wrong with both. I want the solution to be succinct without having to write out alot of np.where statements.

First approach:

JavaScript

incomplete result:

JavaScript

Second approach:

JavaScript

incomplete result:

JavaScript

Desired output for both approaches:

JavaScript

Advertisement

Answer

Use str.extract: create a regex pattern of your search words and try to extract the matched pattern:

JavaScript

Pattern:

JavaScript

b matches the empty string, but only at the beginning or end of a word. The ( ) is the capture group.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement