Recipe: How to filter in a Pandas DataFrame?
DATA MUNGING PYTHON PANDAS DATAFRAME PANDAS DATAFRAME TUTORIAL

How to filter in a Pandas DataFrame?

This recipe helps you filter in a Pandas DataFrame
In [1]:
## How to filter in a Pandas DataFrame
def Kickstarter_Example_87():
    print()
    print(format('How to filter a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd

    # Create Dataframe
    data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
            'year': [2012, 2012, 2013, 2014, 2014],
            'reports': [4, 24, 31, 2, 3],
            'coverage': [25, 94, 57, 62, 70]}

    df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
    print(); print(df)

    # View Column
    print(); print(df['name'])

    # View Two Columns
    print(); print(df[['name', 'reports']])

    # View First Two Rows
    print(); print(df[:2])

    # View Rows Where Coverage Is Greater Than 50
    print(); print(df[df['coverage'] > 50])

    # View Rows Where Coverage Is Greater Than 50 And Reports Less Than 4
    print(); print(df[(df['coverage']  > 50) & (df['reports'] < 4)])

Kickstarter_Example_87()
*************************How to filter a Pandas DataFrame*************************

             name  year  reports  coverage
Cochice     Jason  2012        4        25
Pima        Molly  2012       24        94
Santa Cruz   Tina  2013       31        57
Maricopa     Jake  2014        2        62
Yuma          Amy  2014        3        70

Cochice       Jason
Pima          Molly
Santa Cruz     Tina
Maricopa       Jake
Yuma            Amy
Name: name, dtype: object

             name  reports
Cochice     Jason        4
Pima        Molly       24
Santa Cruz   Tina       31
Maricopa     Jake        2
Yuma          Amy        3

          name  year  reports  coverage
Cochice  Jason  2012        4        25
Pima     Molly  2012       24        94

             name  year  reports  coverage
Pima        Molly  2012       24        94
Santa Cruz   Tina  2013       31        57
Maricopa     Jake  2014        2        62
Yuma          Amy  2014        3        70

          name  year  reports  coverage
Maricopa  Jake  2014        2        62
Yuma       Amy  2014        3        70


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
3 developers from Infosys
2 developers from Accenture
1 developer from Franklin Templeton
1 developer from MudraCircle
1 developer from Vodafone
1 developer from Dhruv Technology Solutions
1 developer from HvH
1 developer from KPMG
1 developer from PwC