Calculate Monthly Average price and plot using Plotly

Viewed 145

I have a Dataframe which contains sold house prices in two areas over a daily period from Oct 2021 till today.

I want to find the average house price per month and plot a graph using plotly to see if prices are going down or up in each area.

Sample DataFrame:

DateSold            Price    Area
12/10/2021 00:00    300000  Area A
17/10/2021 00:00    350000  Area B
18/10/2021 00:00    400000  Area B
11/12/2021 00:00    412000  Area A
17/12/2021 00:00    315000  Area A
08/01/2022 00:00    385000  Area A
09/01/2022 00:00    445000  Area A
15/01/2022 00:00    309000  Area B
15/01/2022 00:00    350000  Area B

I tried to convert the datetime column into a PeriodIndex on monthly frequency, then take the mean using GroupBy.mean:

df2.groupby(pd.PeriodIndex(df2['Datesold'], freq="M"))['Price'].mean()

Can someone point me in the right direction in how I can achieve the average house price per month and plot that using plotly?

I was using the below code for plotly

fig = px.line(df, x = df['DateSold'], y = df['Price'], title='Average sold house price
1 Answers

Your DateTime column does not have a frequency or periodicity. Even if it were the case, you wouldn't need to convert to PeriodIndex. You can group by using the month/month_name of the DateSold column as follows:

# convert object to datetime
df.DateSold = pd.to_datetime(df.DateSold, format="%d/%m/%Y %H:%M")

# compute the monthly averages
df_avg = df.groupby(df.DateSold.dt.month_name(), as_index=True)['Price'].mean()
DateSold
December    363500.0
January     372250.0
October     350000.0

You can then plot the result with plotly

fig = px.bar(df_avg, x = df_avg.index, y = df_avg, title='Average sold house price')
fig
Related