A download file named after the chosen buildings and months

Write code · Medium · §11.5 Editing and optional extensions

The table power holds the monthly electricity use (kWh) of three campus buildings. The starter code picks buildings (Building) and months (Month) in the sidebar and shows the chosen rows, view, as a table. Below it, add a button (st.download_button) that downloads view.

Label the button Download CSV. Its contents are view turned into CSV without the row labels (encoded with encode("utf-8-sig") for Excel), and its file type is text/csv. Name the file after the chosen buildings and months: join the chosen building names with _ in the order they were chosen, then add an underscore, the first month, a hyphen, the last month, and .csv (for example, Gym_Dorm_3-5.csv for Gym and Dorm in months 3 to 5). Grading runs the app again with different widget values and electricity use.

Target figure for A download file named after the chosen buildings and months
Target figure

Starter code

import pandas as pd
import streamlit as st

power = pd.DataFrame({
    "month": [1, 2, 3, 4, 5, 6] * 3,
    "building": ["Library"] * 6 + ["Gym"] * 6 + ["Dorm"] * 6,
    "kwh": [5200, 4800, 4500, 3900, 3600, 3100, 2600, 2500, 2700, 2900, 3100, 3300, 7100, 6800, 6000, 5200, 4700, 4300],
})
st.title("Campus power use")
buildings = st.sidebar.multiselect("Building", ["Library", "Gym", "Dorm"], default=["Library", "Gym", "Dorm"])
months = st.sidebar.slider("Month", 1, 6, (1, 6))
view = power[power["building"].isin(buildings) & power["month"].between(months[0], months[1])]
if view.empty:
    st.warning("Pick at least one building.")
    st.stop()
st.dataframe(view, hide_index=True)

# Write your code here

Solve this problem in your browser

Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.