Streamlit for UIs

Lesson#9 of 9 in project Theory

Display a DataFrame

import streamlit as st
import pandas as pd
df = pd.read_csv("data.csv")
st.dataframe(df)
st.table(df.head(10))  # static table

Basic charts

import streamlit as st
import pandas as pd
df = pd.read_csv("data.csv")
st.line_chart(df["sales"])
st.bar_chart(df["category"].value_counts())
st.area_chart(df[["sales", "profit"]])

Plotly chart

import streamlit as st
import plotly.express as px
fig = px.scatter(df, x="age", y="score", color="name")
st.plotly_chart(fig)

Sidebar filters

age_min = st.sidebar.slider("Min age", 0, 100, 18)
category = st.sidebar.selectbox("Category", df["category"].unique())
filtered = df[(df["age"] >= age_min) & (df["category"] == category)]
st.dataframe(filtered)

File uploader

file = st.file_uploader("Upload CSV", type="csv")
if file:
    df = pd.read_csv(file)
    st.dataframe(df)
    st.write(df.describe())

Metrics

col1, col2, col3 = st.columns(3)
col1.metric("Total rows", len(df))
col2.metric("Avg score", round(df["score"].mean(), 2))
col3.metric("Nulls", df.isnull().sum().sum())

Train a model and show results

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X = df[["age", "score"]]
y = df["label"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = LogisticRegression()
model.fit(X_train, y_train)
acc = model.score(X_test, y_test)
st.success(f"Accuracy: {acc:.2%}")

Show correlation heatmap

import seaborn as sns
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
sns.heatmap(df.corr(), annot=True, ax=ax)
st.pyplot(fig)

Cache heavy operations

@st.cache_data
def load_data(path):
    return pd.read_csv(path)
df = load_data("big_data.csv")  # runs once, cached after