Streamlit: A Quick Guide to Building Interactive Python Apps

calico·2025년 12월 23일

Computer Science

목록 보기
46/51

Streamlit: A Quick Guide to Building Interactive Python Apps

Streamlit is an open-source framework designed to help developers create beautiful, interactive web applications with Python. It’s especially popular for data scientists, machine learning engineers, and anyone who wants to visualize data quickly. With minimal setup, you can turn your Python scripts into interactive applications that run in the browser.

Table of Contents

  1. Installation
  2. Creating Your First App
  3. Streamlit Layout and Widgets
  4. Working with DataFrames
  5. Displaying Charts and Graphs
  6. Integrating Machine Learning Models
  7. Deploying Your Streamlit App
  8. Conclusion

1. Installation

To begin using Streamlit, you first need to install it. Open your terminal or command prompt and run the following command:

pip install streamlit

Once the installation is complete, you’re ready to start building your first app!

2. Creating Your First App

Streamlit makes it super easy to create interactive applications with just a few lines of code. Here’s how to make a basic app:

  1. Create a new Python file (app.py).
  2. Add the following code:
import streamlit as st

# Title of the app
st.title('My First Streamlit App')

# Text input from the user
name = st.text_input("What's your name?")

# Display a greeting
if name:
    st.write(f"Hello, {name}!")
else:
    st.write("Hello, world!")
  1. Save the file and run the app using the following command:
streamlit run app.py

Your app will open in the browser, where you can interact with it.

3. Streamlit Layout and Widgets

Streamlit offers several ways to interact with your users using widgets like sliders, text inputs, and buttons. These widgets make it easy to create dynamic applications.

Using Columns for Layout:

Streamlit allows you to organize your app using columns.

import streamlit as st

col1, col2 = st.columns(2)

with col1:
    st.header('Column 1')
    st.write("This is the first column")

with col2:
    st.header('Column 2')
    st.write("This is the second column")

Interactive Widgets:

  • Text Input (st.text_input()): Allows users to enter text.
  • Slider (st.slider()): Lets users select a value from a range.
  • Button (st.button()): Triggers actions when clicked.
  • Selectbox (st.selectbox()): Lets users choose an option from a list.

Example with a slider:

import streamlit as st

# Slider widget
number = st.slider("Select a number", min_value=0, max_value=100, value=50)

# Display the selected number
st.write(f"You selected {number}")

4. Working with DataFrames

Streamlit makes it easy to display pandas DataFrames directly in your app. You can also modify them interactively.

Here’s how to display a simple table:

import streamlit as st
import pandas as pd

# Sample DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [23, 34, 45],
    'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)

# Display DataFrame
st.write(df)

Streamlit also has st.dataframe() and st.table() for more advanced display options.

5. Displaying Charts and Graphs

Streamlit allows you to add interactive charts and graphs to your app using libraries like Matplotlib, Plotly, and Altair.

Example with Matplotlib:

import streamlit as st
import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Plot the data
plt.plot(x, y)
plt.title("Sine Wave")

# Display the plot in Streamlit
st.pyplot(plt)

Example with Plotly:

You can also use Plotly for interactive charts:

import streamlit as st
import plotly.express as px

# Sample data
df = px.data.iris()

# Create a plot
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")

# Display the plot
st.plotly_chart(fig)

6. Integrating Machine Learning Models

Streamlit is perfect for showcasing machine learning models. For example, if you have a trained model (e.g., using scikit-learn), you can integrate it with your Streamlit app to make real-time predictions.

Here’s a basic example:

import streamlit as st
from sklearn.linear_model import LinearRegression
import numpy as np

# Example model
model = LinearRegression()
model.fit([[1], [2], [3]], [3, 6, 9])

# User input
input_value = st.slider("Select a value", min_value=1, max_value=10, value=5)

# Make a prediction
prediction = model.predict([[input_value]])

# Display the result
st.write(f"The prediction for {input_value} is: {prediction[0]}")

7. Deploying Your Streamlit App

Once you’re happy with your Streamlit app, you’ll want to deploy it so others can use it. Streamlit provides a simple way to deploy your app on Streamlit Cloud. You can also deploy it on other platforms like Heroku or AWS.

Deployment on Streamlit Cloud:

  1. Push your code to GitHub.
  2. Go to Streamlit Cloud and link your GitHub repository.
  3. Streamlit will automatically deploy the app.

8. Conclusion

Streamlit is a powerful tool for quickly creating interactive applications with Python. Whether you’re working with data, visualizations, or machine learning models, Streamlit makes it easy to share your work with others. Its simplicity, rich set of features, and real-time interactivity make it a great choice for both beginners and experienced developers.

profile
개인 블로그

0개의 댓글