How to create PIVOT table using Pandas DataFrame in Python

January 11, 2019

Contact Seller

Guest Post Description

How to create PIVOT table using Pandas DataFrame in Python

def Kickstarter_Example_97(): 
    print()
    print(format('How to create Pivot table using a Pandas DataFrame','*^82'))    
    import warnings
    warnings.filterwarnings("ignore")
    # load libraries
    import pandas as pd
    # Create dataframe
    raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 
                             'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 
                             'Scouts', 'Scouts', 'Scouts', 'Scouts'], 
                'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', 
                            '2nd','1st', '1st', '2nd', '2nd'], 
                'TestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3]}
    df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'TestScore'])
    print(); print(df)
    # Create a pivot table of group means, by company and regiment
    df1 = pd.pivot_table(df, index=['regiment','company'], aggfunc='mean')
    print(); print(df1)
    # Create a pivot table of group score counts, by company and regimensts
    df2 = df.pivot_table(index=['regiment','company'], aggfunc='count')
    print(); print(df2)
    # Create a pivot table of group score max, by company and regimensts
    df3 = df.pivot_table(index=['regiment','company'], aggfunc='max')
    print(); print(df3)
    # Create a pivot table of group score min, by company and regimensts
    df4 = df.pivot_table(index=['regiment','company'], aggfunc='min')
    print(); print(df4)    
Kickstarter_Example_97()

How to create PIVOT table using Pandas DataFrame in Python

Add a Review

You must be logged in to post a comment.