Streamlit: The Amazing Python Library for Data Applications!

Streamlit: The Amazing Python Library for Data Applications!

Hello everyone! Today I want to share an amazing Python library – Streamlit. Are you still struggling with how to present your data analysis results? Are you still worried about creating interactive visual interfaces? With Streamlit, you can easily create beautiful web applications with just a few lines of Python code. It’s like a magic wand that allows us Python data analysts to easily transform into full-stack developers!

What is Streamlit?

Streamlit is a Python library specifically designed for creating web applications for data science. Its uniqueness lies in the fact that you don’t need to know HTML, CSS, or JavaScript; knowing Python is enough! Just like writing a regular Python script, your data analysis process can directly turn into a beautiful web application.

Let’s start with the simplest example:

import streamlit as st

st.title("My First Streamlit App")
st.write("Hello, World!")
name = st.text_input("Please enter your name")
if name:
    st.write(f"Hello, {name}!")

Save the above code as app.py, then run it in the terminal: streamlit run app.py, and you will see a simple web application!

Tip: Installing Streamlit is easy; just run: pip install streamlit

Basic Data Display

Streamlit provides various ways to display data, handling everything from simple text to complex charts with ease:

import streamlit as st
import pandas as pd
import numpy as np

# Create sample data
df = pd.DataFrame({
    'Name': ['Xiao Ming', 'Xiao Hong', 'Xiao Hua'],
    'Age': [18, 20, 19],
    'Score': [85, 92, 88]
})

# Display data table
st.write("### Student Information Table")
st.dataframe(df)  # Interactive data table
st.table(df)      # Static table

# Display chart
st.write("### Score Distribution")
st.bar_chart(df['Score'])  # Bar chart

Interactive Components

The charm of Streamlit lies in its rich interactive components that allow users to operate on data in real-time:

import streamlit as st

# Sidebar controls
st.sidebar.header('Filter Conditions')
age_range = st.sidebar.slider('Age Range', 0, 100, (18, 35))
is_student = st.sidebar.checkbox('Is Student')

# Main page components
option = st.selectbox(
    'Choose your favorite programming language',
    ['Python', 'Java', 'JavaScript', 'C++']
)

if st.button('Confirm Submission'):
    st.write(f'You chose: {option}')
    st.write(f'Age Range: {age_range}')
    st.write(f'Is Student: {is_student}')

Data Visualization

Streamlit perfectly supports mainstream visualization libraries, making your data presentation more vivid:

import streamlit as st
import pandas as pd
import plotly.express as px
import matplotlib.pyplot as plt

# Create interactive chart with plotly
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
st.plotly_chart(fig)

# Create static chart with matplotlib
plt.figure(figsize=(10, 6))
plt.scatter(df["sepal_width"], df["sepal_length"])
plt.title("Iris Data Distribution")
st.pyplot(plt)

Note: When using matplotlib, remember to call st.pyplot() to display the chart

File Upload and Download

Streamlit also supports file uploads and downloads, which is very useful for data analysis applications:

import streamlit as st
import pandas as pd

uploaded_file = st.file_uploader("Select a CSV file to upload", type="csv")
if uploaded_file is not None:
    df = pd.read_csv(uploaded_file)
    st.write("Data Preview:")
    st.write(df.head())
    
    # Process data...
    
    # Provide download functionality
    if st.button('Download Processed Data'):
        csv = df.to_csv(index=False)
        st.download_button(
            label="Download CSV file",
            data=csv,
            file_name='processed_data.csv',
            mime='text/csv',
        )

Practical Layout Tips

Want your application to look more professional? Try these layout tips:

import streamlit as st

# Create multi-column layout
col1, col2, col3 = st.columns(3)
with col1:
    st.write("First Column")
    st.number_input("Input Number", value=0)
with col2:
    st.write("Second Column")
    st.text_input("Input Text")
with col3:
    st.write("Third Column")
    st.button("Click Me")

# Create tabs
tab1, tab2 = st.tabs(["Data Analysis", "Data Visualization"])
with tab1:
    st.write("This is the content for data analysis")
with tab2:
    st.write("This is the content for data visualization")

Tip: Use st.set_page_config() to set the page title, icon, and layout style

Conclusion

Streamlit is truly an impressive tool! Through this article, you have mastered:

  • Creating basic Streamlit applications
  • Displaying data and charts
  • Adding interactive components
  • Handling file uploads and downloads
  • Designing page layouts

I suggest you start trying it out now! You can start with a simple data display and gradually add interactive features. Here’s an exercise: Create a simple data analysis application that allows users to upload a CSV file, select the columns to display, and visualize the data using different charts.

Remember a few tips:

  • Use st.cache_data decorator to cache data and improve application performance
  • st.experimental_rerun() can rerun the entire application
  • Make good use of st.sidebar to place control components and keep the main page tidy

Are you ready? Let’s start creating your first Streamlit application! Looking forward to seeing your work!

Leave a Comment