Skip to content
Advertisement

Update different values in a column based on multiple conditions

I’d like to update values in a column [‘D’] of my data frame based on the substrings contained in column [‘A’]

I have dataframe df, where column D is an exact copy of column A. Column A has list of different cereal names. But I want to check if A contains a certain word and if so, then column D updates to show that word.

For example, If A contains the word Bran then D should update to show Bran. And if column A contains none of the criteria we are looking for then it should return Other.

name Type of Cereal
Bran Cereal Bran
Fiber Cereal Fiber
Nut Cereal Nut

So far I have tried this, but I am not able to change the rest of the columns without any criteria words to ‘Other’

JavaScript

I have also tried creating a function, but I’m not sure how to loop through each value in column A

JavaScript

This just updates the whole column to Fiber.

Any thoughts/suggestions?

Advertisement

Answer

Other way using pandas.Series.str.extract:

JavaScript

Output (Note 4th row in case of no match):

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