Ask Your Question
2

Using Python and Pandas, how can the average price data be organized based on the date after merging the year and month keys?

asked 2022-11-21 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-07-13 19:00:00 +0000

huitzilopochtli gravatar image

Assuming you have a dataframe named df containing the columns year, month, and price, you can merge the year and month columns to create a new column date and then group by this column to calculate the average price for each date as follows:

import pandas as pd

# Merge year and month columns to create date column
df['date'] = pd.to_datetime(df['year'].astype(str) + '-' + df['month'].astype(str), format='%Y-%m')

# Group by date and calculate average price
average_prices = df.groupby('date')['price'].mean()

This will create a new Series object average_prices containing the average price for each date.

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: 2022-11-21 11:00:00 +0000

Seen: 7 times

Last updated: Jul 13 '22