Streamlit
Streamlit
A Python data app framework. Rapid prototyping.
Streamlit
A Python data app framework. Rapid prototyping.
Streamlit is an open-source data app framework for Python developers. Without complex front-end knowledge, you can build interactive web applications in just a few minutes using only pure Python code.
Through Streamlit Cloud, one-click deployment is possible via GitHub integration, and Community Cloud hosts public apps for free. Data scientists can quickly share ML model demos, dashboards, and data exploration tools.
# app.py
import streamlit as st
import pandas as pd
import numpy as np
# νμ΄μ§ μ€μ
st.set_page_config(
page_title="λ°μ΄ν° λμ보λ",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
# μ λͺ©κ³Ό μ€λͺ
st.title("π λ°μ΄ν° λΆμ λμ보λ")
st.markdown("""
μ΄ λμ보λλ **μ€μκ° λ°μ΄ν° λΆμ**μ μν μΈν°λν°λΈ λꡬμ
λλ€.
μ¬μ΄λλ°μμ μ΅μ
μ μ‘°μ ν΄ λ³΄μΈμ!
""")
# μ¬μ΄λλ° μ€μ
st.sidebar.header("μ€μ ")
data_size = st.sidebar.slider("λ°μ΄ν° ν¬κΈ°", 100, 1000, 500)
chart_type = st.sidebar.selectbox("μ°¨νΈ νμ
", ["Line", "Bar", "Area"])
# μν λ°μ΄ν° μμ±
@st.cache_data
def generate_data(size):
dates = pd.date_range(start="2024-01-01", periods=size)
return pd.DataFrame({
"λ μ§": dates,
"λ§€μΆ": np.random.randint(1000, 5000, size),
"λΉμ©": np.random.randint(500, 2000, size),
"μ΄μ΅": np.random.randint(200, 1500, size)
})
df = generate_data(data_size)
# λ©νΈλ¦ νμ
col1, col2, col3 = st.columns(3)
with col1:
st.metric("μ΄ λ§€μΆ", f"${df['λ§€μΆ'].sum():,.0f}", "+12%")
with col2:
st.metric("νκ· λΉμ©", f"${df['λΉμ©'].mean():,.0f}", "-5%")
with col3:
st.metric("μμ΄μ΅", f"${df['μ΄μ΅'].sum():,.0f}", "+8%")
# μ°¨νΈ νμ
st.subheader(f"{chart_type} μ°¨νΈ")
chart_data = df.set_index("λ μ§")[["λ§€μΆ", "λΉμ©"]]
if chart_type == "Line":
st.line_chart(chart_data)
elif chart_type == "Bar":
st.bar_chart(chart_data)
else:
st.area_chart(chart_data)
# λ°μ΄ν° ν
μ΄λΈ (νμ₯ κ°λ₯)
with st.expander("π μμΈ λ°μ΄ν° 보기"):
st.dataframe(df, use_container_width=True)
import streamlit as st
# Session State μ΄κΈ°ν
if "counter" not in st.session_state:
st.session_state.counter = 0
if "messages" not in st.session_state:
st.session_state.messages = []
# μ½λ°± ν¨μ
def increment_counter():
st.session_state.counter += 1
def add_message():
if st.session_state.new_message:
st.session_state.messages.append(st.session_state.new_message)
st.session_state.new_message = "" # μ
λ ₯ νλ μ΄κΈ°ν
# UI
st.header("Session State λ°λͺ¨")
# μΉ΄μ΄ν°
col1, col2 = st.columns(2)
with col1:
st.button("μΉ΄μ΄ν° μ¦κ°", on_click=increment_counter)
st.write(f"νμ¬ μΉ΄μ΄ν°: {st.session_state.counter}")
# λ©μμ§ λ¦¬μ€νΈ
with col2:
st.text_input("λ©μμ§ μΆκ°", key="new_message", on_change=add_message)
for i, msg in enumerate(st.session_state.messages):
st.write(f"{i+1}. {msg}")
import streamlit as st
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
st.title("π€ ML λͺ¨λΈ λ°λͺ¨")
# νμΌ μ
λ‘λ
uploaded_file = st.file_uploader("CSV νμΌμ μ
λ‘λνμΈμ", type=["csv"])
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.subheader("λ°μ΄ν° 미리보기")
st.dataframe(df.head())
# μ»¬λΌ μ ν
st.subheader("λͺ¨λΈ μ€μ ")
target_col = st.selectbox("νκ² μ»¬λΌ", df.columns)
feature_cols = st.multiselect(
"νΌμ² 컬λΌ",
[c for c in df.columns if c != target_col]
)
if feature_cols and st.button("λͺ¨λΈ νμ΅"):
with st.spinner("λͺ¨λΈ νμ΅ μ€..."):
X = df[feature_cols]
y = df[target_col]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
st.success(f"λͺ¨λΈ νμ΅ μλ£! μ νλ: {accuracy:.2%}")
# νΌμ² μ€μλ
importance_df = pd.DataFrame({
"Feature": feature_cols,
"Importance": model.feature_importances_
}).sort_values("Importance", ascending=False)
st.bar_chart(importance_df.set_index("Feature"))
# λλ ν 리 ꡬ쑰
# my_app/
# βββ Home.py # λ©μΈ νμ΄μ§ (streamlit run Home.py)
# βββ pages/
# βββ 1_π_Data.py # 첫 λ²μ§Έ νμ΄μ§
# βββ 2_π_Charts.py # λ λ²μ§Έ νμ΄μ§
# βββ 3_βοΈ_Settings.py
# Home.py
import streamlit as st
st.set_page_config(page_title="λ©ν° νμ΄μ§ μ±", page_icon="π ")
st.title("π ννμ΄μ§")
st.markdown("""
μ¬μ΄λλ°μμ λ€λ₯Έ νμ΄μ§λ‘ μ΄λν μ μμ΅λλ€.
- π Data: λ°μ΄ν° λΆμ
- π Charts: μκ°ν
- βοΈ Settings: μ€μ
""")
# pages/1_π_Data.py
import streamlit as st
import pandas as pd
st.title("π λ°μ΄ν° λΆμ")
# νμ΄μ§λ³ 컨ν
μΈ ...
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Streamlit re-runs the entire script on every interaction. If you do not use session_state, state is not preserved, so be sure to store user input and calculation results in st.session_state.
Use @st.cache_data for serializable data (DataFrame, dict) and @st.cache_resource for non-serializable objects (ML models, DB connections). If used incorrectly, errors occur or caching does not work properly.
Because Streamlit runs single-threaded, performance degrades when there are many concurrent users. In a production environment, run multiple instances or check the limits of Streamlit Community Cloud.
When creating widgets inside a loop, you must specify a unique key parameter. If the key is duplicated, a "DuplicateWidgetID" error occurs.
Use st.secrets to manage API keys and sensitive information. Be careful not to hard-code them directly in the code or commit .env files, and add secrets.toml to .gitignore.
Provides API reference, tutorials, and guides
docs.streamlit.ioA community for questions, discussions, and showcases
discuss.streamlit.ioA platform for free app hosting and deployment
streamlit.io/cloud