PDA

View Full Version : Pandas DataFrame Manipulation Issue: Calculating Monthly Average from Daily Data



mark01
08-22-2023, 05:26 AM
I'm working on a data analysis project using Python and Pandas, and I'm facing an issue with manipulating a DataFrame that contains daily data. I have a DataFrame with two columns: date and value. I want to calculate the monthly average of the value column based on the daily data.


Here's a simplified version of my code:


import pandas as pd


# Sample data
data = {'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-02-01', '2023-02-02'],
'value': [10, 15, 20, 5, 8]}


df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])


# Calculate monthly average
monthly_avg = df.resample('M', on='date').mean()




When I run this code, the monthly_avg DataFrame seems to have NaN values for all the rows. I suspect this is because I don't have data for every day in a month. Is there a way to calculate the monthly average even if I have missing days within a month? Or do I need to preprocess the data differently before calculating the monthly average? I have looked on other websites, but I was unable to find the answer. I would appreciate any advice on how to correctly compute the monthly average using Pandas from this daily data. I appreciate your help in advance.

Aussiebear
08-22-2023, 07:05 AM
mark01, as I have previously indicated to you, this forum is a VBA forum we do not support other languages. If you need assistance in relation to Python, then head to a Python forum.

georgiboy
08-23-2023, 05:25 AM
Python is soon to be included in Excel itself, it is being rolled out to the BETA versions as i type, i believe Pytho can be created in the VBE as well as within a formula of '=PY('

Does not help this thread but thought it worth a mention as VBA & Python are soon to work in harmony.

Aussiebear
08-23-2023, 06:17 AM
That is true Georgiboy, however we are predominately VBA focused, so until the Admin indicate that we also pursue Python for use within Excel, its fundamentally outside the aims of the forum.

georgiboy
08-23-2023, 07:30 AM
We are going to end up being like a car garage that will only work on window wipers. I understand what you are saying though (understand not agree).