Hey, friends! Today I want to introduce you to a super useful Python library – Streamlit. It allows us to create beautiful web applications with simple Python code. No need to know HTML, CSS, or JavaScript; just a few lines of code can turn your data analysis into an interactive webpage! I always think of Streamlit as the “LEGO blocks” of the data science world, simple and fun. Let’s get started building!
1. Quick Start: Your First Streamlit App
First, we need to install Streamlit:
# Type in the command line
pip install streamlit
To create our first app:
# Save as app.py
import streamlit as st
st.title('My First Streamlit App')
st.write('Hello, World!')
# Add a slider
age = st.slider('What is your age?', 0, 100, 25)
st.write(f'Your selected age is: {age}')
Tip: To run the Streamlit app, just type in the command line:
streamlit run app.py
2. Data Display: Making Data Visualization Easy
Streamlit’s support for data display is very friendly, let’s give it a try:
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
df = pd.DataFrame({
'Name': ['Xiao Ming', 'Xiao Hong', 'Xiao Li', 'Xiao Zhang'],
'Age': [25, 28, 22, 30],
'Salary': [8000, 12000, 7000, 15000]
})
# Display data table
st.subheader('Employee Information Table')
st.dataframe(df) # This completes an interactive table!
# Create chart
st.subheader('Salary Distribution Chart')
fig, ax = plt.subplots()
ax.bar(df['Name'], df['Salary'])
st.pyplot(fig)
3. Interactive Widgets: Making the App Lively
Streamlit provides a rich set of interactive widgets, let’s play with them:
# Text input
name = st.text_input('Please enter your name:')
if name:
st.write(f'Hello, {name}!')
# Dropdown selection
option = st.selectbox(
'What is your favorite programming language?',
['Python', 'Java', 'JavaScript', 'C++']
)
st.write(f'You selected: {option}')
# Multi-select box
hobbies = st.multiselect(
'Your hobbies:',
['Reading', 'Sports', 'Music', 'Traveling', 'Programming']
)
st.write('Your interests are:', hobbies)
# Button interaction
if st.button('Click me'):
st.balloons() # Show balloon animation
4. Data Upload and Processing: Practical Features Arrive
Let’s create a simple file upload and data analysis app:
import streamlit as st
import pandas as pd
import plotly.express as px
st.title('CSV File Analyzer')
# File upload
uploaded_file = st.file_uploader("Select a CSV file", type="csv")
if uploaded_file is not None:
# Read data
df = pd.read_csv(uploaded_file)
# Display basic information
st.write("Data Preview:")
st.dataframe(df.head())
# Display statistics
st.write("Basic Statistics:")
st.write(df.describe())
# Select column to plot
columns = df.select_dtypes(include=['float64', 'int64']).columns
selected_column = st.selectbox('Select a column to plot histogram:', columns)
# Plot histogram
fig = px.histogram(df, x=selected_column)
st.plotly_chart(fig)
5. Layout Beautification: Making the App More Professional
Streamlit provides various layout options:
# Using column layout
col1, col2 = st.columns(2)
with col1:
st.subheader('Left Column')
st.write('This is the content on the left side')
with col2:
st.subheader('Right Column')
st.write('This is the content on the right side')
# Using expander
with st.expander('Click to expand details'):
st.write('Here are some long details...')
st.image('https://streamlit.io/images/brand/streamlit-mark-color.png')
Note: Streamlit pages are executed from top to bottom. If you want to change the position of an element, you need to adjust the order of the code.
Practical Exercises
Try these interesting exercises:
-
Create a simple to-do list app (Tip: use st.checkbox) -
Make a data visualization dashboard to show real-time temperature data -
Build a simple image processing app (Tip: use the PIL library)
Summary
Today we learned the basic features of Streamlit:
-
Usage of basic components -
Data display and visualization -
Application of interactive widgets -
File upload and processing -
Page layout techniques
Streamlit is truly a magical tool that allows us to quickly turn Python scripts into beautiful web applications. Remember, the most important thing in learning programming is hands-on practice!
Advanced Tips:
Try using st.cache to optimize performance Explore Streamlit’s theme customization Learn how to deploy Streamlit apps to the cloud
Next time we will explore more advanced features of Streamlit. Until then, go ahead and create your own first Streamlit app!
Let’s use Streamlit to turn boring data into lively stories!