Title: Select Rows When Columns Contain Certain Values
Slug: pandas_select_rows_when_column_has_certain_values
Summary: Select Rows When Columns Contain Certain Values
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon
In [1]:
# Import modules
import pandas as pd
# Set ipython's max row display
pd.set_option('display.max_row', 1000)
# Set iPython's max column width to 50
pd.set_option('display.max_columns', 50)
In [2]:
# Create an example dataframe
data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'year': [2012, 2012, 2013, 2014, 2014],
'reports': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df
Out[2]:
In [3]:
value_list = ['Tina', 'Molly', 'Jason']
In [4]:
#Grab DataFrame rows where column has certain values
df[df.name.isin(value_list)]
Out[4]:
In [5]:
#Grab DataFrame rows where column doesn't have certain values
df[~df.name.isin(value_list)]
Out[5]: