- Contents
- Applied concepts
- Prerequisites
- Summary
- Build the example
- Initialize your app
- Build a function to create random member data
- Display your data with multi-row selections enabled
- Display the selected data
- Combine activity data for the selected rows
- Use charts to visualize the activity comparison
- Make it pretty
Get dataframe row-selections from users
Streamlit offers two commands for rendering beautiful, interactive dataframes in your app. If you need users to edit data, add rows, or delete rows, use st.data_editor. If you don't want users to change the data in your dataframe, use st.dataframe. Users can sort and search through data rendered with st.dataframe. Additionally, you can activate selections to work with users' row and column selections.
This tutorial uses row selections, which were introduced in Streamlit version 1.35.0. For an older workaround using st.data_editor, see Get dataframe row-selections (streamlit<1.35.0).
Applied concepts
- Use dataframe row selections to filter a dataframe.
Prerequisites
-
This tutorial requires the following version of Streamlit:
Text -
You should have a clean working directory called
your-repository. -
You should have a basic understanding of caching and
st.dataframe.
Summary
In this example, you'll build an app that displays a table of members and their activity for an imaginary organization. Within the table, a user can select one or more rows to create a filtered view. Your app will show a combined chart that compares the selected employees.
Here's a look at what you'll build:
Build the example
Initialize your app
-
In
your_repository, create a file namedapp.py. -
In a terminal, change directories to
your_repository, and start your app:TerminalYour app will be blank because you still need to add code.
-
In
app.py, write the following:PythonYou'll be using these libraries as follows:
- You'll generate random member names with
faker. - You'll generate random activity data with
numpy. - You'll manipulate the data with
pandas.
- You'll generate random member names with
-
Save your
app.pyfile, and view your running app. -
In your app, select "Always rerun", or press the "A" key.
Your preview will be blank but will automatically update as you save changes to
app.py. -
Return to your code.
Build a function to create random member data
To begin with, you'll define a function to randomly generate some member data. It's okay to skip this section if you just want to copy the function.
-
Use an
@st.cache_datadecorator and start your function definition.PythonThe
@st.cache_datadecorator turnsget_profile_dataset()into a cached function. Streamlit saves the output of a cached function to reuse when the cached function is called again with the same inputs. This keeps your app performant when rerunning as part of Streamlit's execution model. For more information, see Caching.The
get_profile_datasetfunction has two parameters to configure the size of the data set and the seed for random generation. This example will use the default values (20 members in the set with a seed of 0). The function will return apandas.DataFrame. -
Initialize an empty list to store data.
Python -
Initialize the random generators.
Python -
Iterate through a range to generate new member data as a dictionary and append it to your list.
PythonFor
daily_activity, you're generating an array of length 25. These values are floats in the interval[0,1). Foractivity, you're generating an array of length 12. These values are integers in the interval[2,90). -
Convert your list of dictionaries to a single
pandas.DataFrameand return it.Python -
Optional: Test out your function by calling it and displaying the data.
PythonSave your
app.pyfile to see the preview. Delete this line before you continue.
Display your data with multi-row selections enabled
-
Define your column configuration to format your data.
PythonFor each column of your dataframe, this defines nicely formatted column name, tooltip, and column width. You'll use a line chart to show yearly activity, and a bar chart to show daily activity.
-
Insert a header to identify the data you will display.
Python -
Store your data in a convenient variable.
Python -
Display your dataframe with selections activated.
PythonBy setting
on_selection="rerun", you've activated selections for the dataframe.selection_mode="multi_row"specifies the type of selections allowed (multiple rows, no columns).eventstores the selection data from the user. Selections can be accessed from theevent.selectionattribute.
Display the selected data
-
Insert a header to identify the subset of data you will display.
Python -
Get the list of selected rows and filter your dataframe.
PythonRow selections are returned by positional index. You should use pandas methods
.iloc[]or.iat[]to retrieve rows. -
Display the selected rows in a new dataframe.
PythonFor consistency, reuse the existing column configuration.
-
Optional: Save your file and test it out. Try selecting some rows in your app, and then return to your code.
Combine activity data for the selected rows
-
Create an empty dictionary to store (yearly) activity data.
Python -
Iterate through selected rows and save each member's activity in the dictionary indexed by their name.
Python -
Convert the activity dictionary into a
pandas.DataFrame.Python -
Repeat the previous three steps similarly for daily activity.
Python -
Optional: Test out your combined data by displaying it.
PythonSave your
app.pyfile to see the preview. Delete these two lines before you continue.
Use charts to visualize the activity comparison
-
Start a conditional block to check if anyone is currently selected.
PythonSince no members are selected when the app loads, this check will prevent empty charts from being displayed.
-
Add a header to identify your first chart.
Python -
Show the daily activity comparison in a bar chart.
Python -
Similarly, for yearly activity, add a header and line chart.
Python -
Complete the conditional block with a default message to show when no members are selected.
Python
Make it pretty
You should have a functioning app at this point. Now you can beautify it. In this section, you'll separate the selection UI from the comparison by using st.tabs.
-
Immediately after the column configuration definition, insert two tabs.
Python -
Indent the code following the line in the previous step and group it into the two new tabs.
Python -
Save your file and try out your completed example.
Still have questions?
Our forums are full of helpful information and Streamlit experts.
