Skip to content
Advertisement

filter string elements from list using another list

I have a list of strings of various lengths stored in df. The total number of rows in df is 301501. Example is as follows:

JavaScript

I have also stored a list of female names in another list called f_name.

I want to create another column in df to filter out elements that are not found in f_name. What I tried was this:

JavaScript

The error received is “ValueError: Length of values (0) does not match length of index (301501)”. How do I create a new column with a filtered list that only contains elements from f_name?

Advertisement

Answer

Assuming your item column actually contains lists of strings (and aren’t just strings that look like lists, e.g. '[1, 2, 3]'), cast f_name to set and perform set intersection:

JavaScript

Demo:

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