[SOLVED] Check if Python list elements are in a Pandas dataframe row and append to a new column

Issue

I have a dataframe like this:

Casa Name
Solo Deportes Paleta De Padel Adidas Metalbone CTRL
Solo Deportes Zapatillas Running Under Armour Charged Stamin…
Solo Deportes Rompeviento Con Capucha Reebok Woven Azu

and a List:

Maestro_Marcas=[‘Adidas’, ‘Reebebok’,’Under Armour’]

How can I check each row of df[‘Name’], see if the row contains a value of the list, and in that case get the value of the list and put it in the new column?. The result should be something like this:

Casa Name Marca
Solo Deportes Paleta De Padel Adidas Metalbone CTRL Adidas
Solo Deportes Zapatillas Running Under Armour Charged Stamin… Under Armour
Solo Deportes Rompeviento Con Capucha Reebok Woven Azu Reebok

Solution

You can try findall

df['Marca'] = df['Name'].str.findall('|'.join(Maestro_Marcas))

Notice,it will return a list of finding, if two items found within one Name, it will return both.

To match the output you need

 df['Marca'] = df['Name'].str.findall('|'.join(Maestro_Marcas)).str[0]

Answered By – BENY

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *