Ask Your Question
4

How can I calculate the total purchases per month when I have a pandas dataframe with two columns, where one column consists of repeating months and the other has purchase values?

asked 2023-05-21 08:35:14 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-21 08:56:02 +0000

lakamha gravatar image

You can use pandas' groupby and sum functions to calculate the total purchases per month. Here's an example code:

import pandas as pd

# create sample dataframe
df = pd.DataFrame({'month': ['Jan', 'Jan', 'Feb', 'Feb'],
                   'purchase_value': [100, 200, 150, 250]})

# group by month and sum purchase values
monthly_total = df.groupby('month')['purchase_value'].sum()

# print the result
print(monthly_total)

Output:

month
Feb    400
Jan    300
Name: purchase_value, dtype: int64

In this example, we first create a sample dataframe with two columns: "month" and "purchasevalue". Then, we use the groupby function to group the dataframe by "month", and then apply the sum function to calculate the total purchases per month for the "purchasevalue" column. Finally, we print the result.

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-05-21 08:35:14 +0000

Seen: 9 times

Last updated: May 21 '23