moving average in pythn in python

To calculate the moving average in Python, you can use the pandas library. Here is an example of how to do it:

main.py
import pandas as pd

# create a sample dataset
data = {'Date': ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
        'Value': [10, 20, 30, 40, 50]}
df = pd.DataFrame(data)

# calculate the moving average with a window of 3
window_size = 3
df['Moving Average'] = df['Value'].rolling(window=window_size).mean()

# print the result
print(df)
365 chars
14 lines

Output:

main.py
         Date  Value  Moving Average
0  2021-01-01     10             NaN
1  2021-01-02     20             NaN
2  2021-01-03     30       20.000000
3  2021-01-04     40       30.000000
4  2021-01-05     50       40.000000
222 chars
7 lines

In the above example, we create a pandas dataframe with two columns - Date and Value. We then calculate the moving average using the rolling() function and specify the window size as 3. The moving average values are added as a new column in the dataframe. Finally, we print the dataframe to see the result.

related categories

gistlibby LogSnag