SoFunction
Updated on 2025-04-13

Python uses Streamlit to quickly build a data application

introduction

In the fields of data science and machine learning, building data applications often means investing a lot of time and effort in developing user interfaces (UIs) and backend logic. However, with the advent of Streamlit, the process has become unprecedentedly simple and efficient. Streamlit is an open source Python library that allows data scientists and developers to quickly create and share data applications without the need for complex web development experience. This article will introduce the basic usage of Streamlit and demonstrate how to quickly build a simple data application through a practical case.

1. Introduction to Streamlit

Streamlit is a tool designed for data scientists that allows you to build interactive web applications using Python code. Streamlit allows you to easily embed data analysis, machine learning models, and visualization results into an intuitive interface for others to view and interact with. The core advantage of Streamlit is its ease of use and flexibility, which allows data scientists to focus on the data itself rather than spending a lot of time on UI design.

2. Basic usage of Streamlit

Before using Streamlit, you need to make sure that Python and pip are installed. Then, you can install Streamlit via pip:

pip install streamlit

After the installation is complete, you can start a Streamlit application with the following command:

streamlit hello

This command will launch a default Streamlit application, showing some basic Streamlit functions.

To create your own Streamlit application, you need to write a Python script and build the UI using the API provided by Streamlit. Here is a simple example showing how to create an interface with text input boxes and buttons in Streamlit:

import streamlit as st
 
# Set the title('My first Streamlit application')
 
# Create a text input boxuser_input = st.text_input('Please enter some text:')
 
# Create a buttonif ('Click me'):
    ('You clicked the button!  The input text is:', user_input)

Save the above code as a Python file (for example), and then run the following command on the command line to start the Streamlit application:

streamlit run 

Open the browser and access the displayed local address (usually http://localhost:8501), and you will see a web interface with a text input box and button.

3. Advanced usage of Streamlit

In addition to basic text input boxes and buttons, Streamlit also supports a variety of UI components, including check boxes, radio buttons, sliders, file uploads, etc. In addition, Streamlit can also seamlessly integrate with common data analysis and visualization tools such as Pandas DataFrame, Matplotlib charts, and Plotly charts.

1. Use Pandas DataFrame

Streamlit can easily display Pandas DataFrame and support filtering, sorting and other operations. Here is an example:

import streamlit as st
import pandas as pd
 
# Create a sample DataFramedata = {
    'Name': ['Zhang San', 'Li Si', 'Wang Wu'],
    'age': [23, 28, 22],
    'City': ['Beijing', 'Shanghai', 'Guangzhou']
}
df = (data)
 
# Set the title('DataFrame Example')
 
# Show DataFrame(df)

2. Use Matplotlib and Plotly for visualization

Streamlit supports integration with visual libraries such as Matplotlib and Plotly, making data visualization very simple. Here is an example of drawing a line chart using Matplotlib:

import streamlit as st
import  as plt
import numpy as np
 
# Set the title('Matplotlib line chart example')
 
# Generate datax = (0, 10, 100)
y = (x)
 
# Draw a line chart(x, y)
(fig=())  # Use the display chart

Similarly, you can use Plotly to create more complex visualizations:

import streamlit as st
import  as px
import pandas as pd
 
# Create a sample DataFramedata = {
    'date': pd.date_range(start='2023-01-01', periods=100),
    'value': (100).cumsum()
}
df = (data)
 
# Set the title('Plotly line chart example')
 
# Use Plotly to draw a line chartfig = (df, x='date', y='value')
st.plotly_chart(fig)

3. Create interactive controls

Streamlit also supports the creation of interactive controls such as sliders, check boxes, radio buttons, etc., which can interact with your data analysis and visual code. Here is an example of using a slider to control the X-axis range of the line graph:

import streamlit as st
import  as plt
import numpy as np
 
# Set the title('Interactive Slider Example')
 
# Generate datax = (0, 10, 100)
y = (x)
 
# Create a slider to control the X-axis rangeslider_value = ('Select X-axis range', 0.0, 10.0, (0.0, 10.0))
 
# Intercept data based on slider valuex_selected = x[np.logical_and(x >= slider_value[0], x <= slider_value[1])]
y_selected = y[np.logical_and(x >= slider_value[0], x <= slider_value[1])]
 
# Draw a line chart(x_selected, y_selected)
(fig=())

4. Practical case: Building a simple data application

Below, we will show you how to build a simple data application using Streamlit with a practical example. This application will allow users to upload a CSV file and display statistical summary and visual charts of the data on the interface.

First, you need to write a Python script (such as data_app.py) and include the following code:

import streamlit as st
import pandas as pd
import  as plt
import seaborn as sns
 
# Set the title and page layout('Data application example')
col1, col2 = st.beta_columns(2)
 
# Upload CSV fileuploaded_file = col1.file_uploader("Upload CSV file", type=["csv"])
 
if uploaded_file is not None:
    # Read CSV file    df = pd.read_csv(uploaded_file)
    
    # Display the first few lines of the data    ("Data Preview:")
    (())
    
    # Statistical summary of displaying data    ("Summary of statistics:")
    (())
    
    # Draw data visualization charts    ("Data Visualization")
    
    # Select the drawing column    x_col = ("Select X-axis column", )
    y_col = ("Select Y-axis column", )
    
    # Draw a scatter plot    (figsize=(8, 6))
    (data=df, x=x_col, y=y_col)
    (fig=())

Then, run the following command in the command line to start the Streamlit application:

streamlit run data_app.py

Open the browser and access the displayed local address, and you will see a web interface with a file upload box, data preview, statistical summary and visual charts. You can upload a CSV file and view and analyze the data on the interface.

5. Summary and Outlook

Streamlit is a powerful and easy to use Python library that enables data scientists and developers to quickly build and share data applications. Through the introduction and examples of this article, you should have mastered the basic usage and advanced techniques of Streamlit and be able to use Streamlit to create your own data applications.

With the continuous development and improvement of Streamlit, it will support more UI components and advanced features, making the construction of data applications simpler and more efficient. At the same time, the Streamlit community is expanding, and you can communicate and collaborate with other data scientists and developers by participating in community discussions and sharing your own applications and code.

In short, Streamlit is a data application building tool worth a try, which will help you transform data analytics and machine learning models into interactive web applications faster and bring more convenience and fun to your work.

The above is the detailed content of Python using Streamlit to quickly build data applications. For more information about Python Streamlit data applications, please follow my other related articles!