the app display sales by month as a tabular table, sales as row, month as column and sales as the value. when user click on the sales of a given month, a drill down of the sales by product of previous month, current month and next month are included
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
# Generate sample data
def generate_sample_data():
np.random.seed(42)
products = ['Laptop', 'Phone', 'Tablet', 'Watch', 'Headphones']
months = pd.date_range(start='2023-01-01', end='2023-12-31', freq='M')
data = []
for month in months:
for product in products:
sales = np.random.randint(50, 500)
data.append({
'Month': month,
'Product': product,
'Sales': sales
})
return pd.DataFrame(data)
# Initialize session state
if 'df' not in st.session_state:
st.session_state.df = generate_sample_data()
st.session_state.selected_month = None
st.title('Monthly Sales Dashboard')
# Create pivot table for monthly totals
pivot_df = st.session_state.df.pivot_table(
index='Product',
columns=pd.Grouper(key='Month', freq='M'),
values='Sales',
aggfunc='sum'
).sum()
# Display total monthly sales
st.subheader('Monthly Sales')
monthly_sales = pd.DataFrame(pivot_df).T
monthly_sales.index = monthly_sales.index.strftime('%Y-%m')
st.dataframe(monthly_sales, use_container_width=True)
# Handle click on monthly sales
clicked = st.data_editor(
monthly_sales,
disabled=True,
hide_index=False,
use_container_width=True,
key='clickable_table'
)
if clicked['edited_rows']:
selected_month = list(clicked['edited_rows'].keys())[0]
st.session_state.selected_month = pd.to_datetime(selected_month)
# Show drill-down if month is selected
if st.session_state.selected_month:
st.subheader(f'Sales Drill-down for {st.session_state.selected_month.strftime("%Y-%m")}')
# Get previous, current and next month data
selected_date = st.session_state.selected_month
prev_month = selected_date - pd.DateOffset(months=1)
next_month = selected_date + pd.DateOffset(months=1)
# Filter data for these months
mask = (st.session_state.df['Month'].isin([prev_month, selected_date, next_month]))
drill_down_data = st.session_state.df[mask].copy()
# Create pivot table for drill-down
drill_down_pivot = drill_down_data.pivot_table(
index='Product',
columns='Month',
values='Sales',
aggfunc='sum'
)
# Format column headers
drill_down_pivot.columns = drill_down_pivot.columns.strftime('%Y-%m')
# Display drill-down table
st.table(drill_down_pivot)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?