Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

How can I achieve the equivalents of SQL's IN and NOT IN?

I have a list with the required values. Here's the scenario:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']}) countries_to_keep = ['UK', 'China']  # pseudo-code: df[df['country'] not in countries_to_keep] 

My current way of doing this is as follows:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']}) df2 = pd.DataFrame({'country': ['UK', 'China'], 'matched': True})  # IN df.merge(df2, how='inner', on='country')  # NOT IN not_in = df.merge(df2, how='left', on='country') not_in = not_in[pd.isnull(not_in['matched'])] 

But this seems like a horrible kludge. Can anyone improve on it?

like image 272
LondonRob Avatar asked Nov 13 '13 17:11

LondonRob


People also ask

Which filtering method is possible on pandas?

Filter Pandas Dataframe by Row and Column Position We can use df. iloc[ ] function for the same.

Is in function in pandas?

Definition and Usage. The isin() method checks if the Dataframe contains the specified value(s). It returns a DataFrame similar to the original DataFrame, but the original values have been replaced with True if the value was one of the specified values, otherwise False .

How do you use not in filter?

How to Use “not in” operator in Filter, To filter for rows in a data frame that is not in a list of values, use the following basic syntax in dplyr. df %>% filter(! col_name %in% c('value1', 'value2', 'value3', ...)) df %>% filter(!


1 Answers

You can use pd.Series.isin.

For "IN" use: something.isin(somewhere)

Or for "NOT IN": ~something.isin(somewhere)

As a worked example:

import pandas as pd  >>> df   country 0        US 1        UK 2   Germany 3     China >>> countries_to_keep ['UK', 'China'] >>> df.country.isin(countries_to_keep) 0    False 1     True 2    False 3     True Name: country, dtype: bool >>> df[df.country.isin(countries_to_keep)]   country 1        UK 3     China >>> df[~df.country.isin(countries_to_keep)]   country 0        US 2   Germany 
like image 149
DSM Avatar answered Oct 16 '22 02:10

DSM