Ask Your Question
1

How to compute the sum of values in a pandas dataframe based on months?

asked 2023-07-18 15:01:06 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-18 15:09:02 +0000

plato gravatar image

To compute the sum of values in a pandas dataframe based on months, you can use the groupby() function along with the resample() function.

Assuming you have a dataframe called 'df' with a datetime column called 'date' and a value column called 'value', here's an example code snippet to compute the sum of values based on months:

df['date'] = pd.to_datetime(df['date']) # Convert date column to datetime format if not already done

df.set_index('date', inplace=True) # Set date column as index

monthly_sum = df.resample('M').sum() # Resample data by month and compute sum of values

print(monthly_sum) # Print monthly sum dataframe

The resample() function with argument 'M' resamples the data by month, computing the monthly sum of values. The resulting dataframe 'monthly_sum' will have the sum of values for each month, with a datetime index representing the end of each month.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-18 15:01:06 +0000

Seen: 11 times

Last updated: Jul 18 '23