Filter pandas dataframe by list

Viewed 18097

I have a dataframe that has a row called "Hybridization REF". I would like to filter so that I only get the data for the items that have the same label as one of the items in my list.

Basically, I'd like to do the following:

dataframe[dataframe["Hybridization REF"].apply(lambda: x in list)] 

but that syntax is not correct.

6 Answers

You can try the following:

df.loc[ df.index.intersection(lst), : ]

This way you only get the intersection

Another alternative is to use query:

df.query('`Hybridization REF` == @list')

The `'s before and after Hybridization REF are needed due to the whitespace in the column name. With @ you can access the variable list.

Keep in mind that Python's built-in list type is named list. So it is a good idea to rename this variable.

Same code with this correction should work.

dataframe[dataframe["Hybridization REF"].apply(lambda x : x in list)] 
Related