You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python Streamlit中为数据表格添加筛选复选框?

Adding Filter Checkboxes to Your Streamlit Sales Report

Hey there! Adding filter checkboxes to your Streamlit sales report is totally doable—let me walk you through how to integrate them with your existing code. I'll cover two common scenarios: multi-option category filters (using a checkbox-style selector) and single yes/no filters.

Multi-Option Filter (Checkbox Selector)

This is perfect if you want users to filter your data by categories like product type, region, or sales quarter. Here's how to modify your code:

import pandas as pd
import streamlit as st
import plotly.express as px
from PIL import Image

st.set_page_config(page_title='Sales Report')
st.header('Sales Report')
st.subheader('Results')

# Read your data (note: make sure your file path includes the .csv suffix if it's a CSV file)
df = pd.read_csv('data.csv')

# 1. Define which column you want to filter by (replace with your actual column name)
filter_column = "Product Category"
# 2. Get all unique values from that column to use as filter options
filter_options = df[filter_column].unique()

# 3. Create a multi-select checkbox widget (users can pick multiple options)
selected_filters = st.multiselect(
    f"Filter by {filter_column}",
    filter_options,
    default=filter_options  # Default to showing all options initially
)

# 4. Filter the dataframe to only include rows matching selected options
filtered_df = df[df[filter_column].isin(selected_filters)]

# 5. Display the filtered table
st.dataframe(filtered_df)

Key Notes:

  • Replace Product Category with the actual column name from your dataset (e.g., Region, Sales Year, Product Line).
  • The st.multiselect widget acts like a group of checkboxes—users can select multiple values at once.
  • Setting default=filter_options ensures all data is shown when the app first loads, matching your current behavior.

Single Checkbox Filter (Yes/No Condition)

If you have a binary condition (like "show only high-value sales" or "display in-stock items"), use a single checkbox:

import pandas as pd
import streamlit as st
import plotly.express as px
from PIL import Image

st.set_page_config(page_title='Sales Report')
st.header('Sales Report')
st.subheader('Results')

df = pd.read_csv('data.csv')

# Create a single checkbox for a binary filter
show_high_value_only = st.checkbox("Show only sales over $1000")

# Filter based on the checkbox state
if show_high_value_only:
    filtered_df = df[df["Sales Amount"] > 1000]
else:
    filtered_df = df

st.dataframe(filtered_df)

Just replace Sales Amount and the condition (> 1000) with your actual column and filter logic.

内容的提问来源于stack exchange,提问作者Manas Jadhav

火山引擎 最新活动