How to calculate MOVING AVERAGE in Pandas DataFrame in Python

January 10, 2019

Contact Seller

Guest Post Description

How to calculate MOVING AVERAGE in Pandas DataFrame in Python

def Kickstarter_Example_95(): 
    print()
    print(format('How to calculate MOVING AVG in a Pandas DataFrame','*^82'))    
    import warnings
    warnings.filterwarnings("ignore")
    # load libraries
    import pandas as pd
    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'], 
                'name': ['Miller', 'Jacobson', 'Bali', 'Milner', 'Cooze', 'Jacon', 
                         'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 
                'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
                'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
    df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 
                                           'preTestScore', 'postTestScore'])    
    print(); print(df)

    # Calculate Rolling Moving Average with Window of 2
    df1 = df.rolling(window=2).mean()
    print(); print(df1)
    df2 = df1.fillna(0)
    print(); print(df2)
Kickstarter_Example_95()

How to calculate MOVING AVERAGE in Pandas DataFrame in Python

Add a Review

You must be logged in to post a comment.