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


Companies using this Recipe
1 employee of Renovite Technologies
1 employee of IBM
1 employee of S&P Global
1 employee of Altimetrik
1 employee of ICU Medical
1 employee of YASH Technologies
1 employee of ANAC
1 employee of KPMG
1 employee of eClerx
1 employee of LTI