IniziaInizia gratis

Creating nested categories

For your final plot, the estate agents would like you to present property sales across the year, displaying months and quarters on the x-axis.

Some of the code to add months and quarters into the Melbourne dataset has been preloaded for you. The factors variable, which will represent months and their corresponding quarters, needs to be created. The data must be also grouped by these two newly created columns to calculate total sales by taking the sum of the "price" column.

Questo esercizio fa parte del corso

Interactive Data Visualization with Bokeh

Visualizza il corso

Istruzioni dell'esercizio

  • Complete factors, entering the relevant quarters and associated months.
  • Create grouped_melb by grouping melb by "month" and "quarter", calculating the total of the "price" column.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

melb["month"] = melb["date"].dt.month
quarters = {1: "Q1", 2:"Q1", 3:"Q1", 4:"Q2", 5:"Q2", 6:"Q2", 7:"Q3", 8:"Q3", 9:"Q3", 10:"Q4", 11:"Q4", 12:"Q4"}
melb["quarter"] = melb["month"].replace(quarters)
melb["month"] = melb["month"].replace({1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"November", 12:"December"})

# Create factors
factors = [("Q1", "January"), ("____", "February"), ("____", "March"), 
           ("Q2", "April"), ("____", "____"), ("____", "____"), 
           ("Q3", "July"), ("____", "____"), ("____", "____"), 
           ("Q4", "October"), ("____", "____"), ("____", "____")]

# Calculate total sales by month and quarter
grouped_melb = melb.groupby(["____", "____"], as_index=False)["____"].sum()
grouped_melb.sort_values("quarter", inplace=True)
print(grouped_melb.head())
Modifica ed esegui il codice