Skip to content
Advertisement

Python pandas replace based on partial match with list item

I have a large three-column dataframe of this form:

JavaScript

And a long list with entries like this:

JavaScript

I want to replace the entries in the Shaperef column of the df with a value from the list if the full Shaperef string matches any part of any list item. If there is no match, the entry is not changed.

Desired output:

JavaScript

So refs 9, 10, 12 are updated as there is a partial match with a list item. Refs 5, 14 stay as there are.

Advertisement

Answer

If Shaperef and all the entries in li are all strings you can write a function to apply over Shaperef to convert them:

JavaScript

Then:

JavaScript

This might not be a very quick way of doing this as it has a worst case run time of len(df) * len(li).

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