Filter number of rows in a dataframe on user input


I have a pandas data frame with investment data. Two columns - Year and Amount. I want to filter this dataframe(and ultimately a graph of this dataframe) by the years input by the user.

For example the data frame has 50 rows, but I want the user to be able to select a number of years less than 50 to have the dataframe then only show the number of years the user inpput so that my graph only shows the years the user input.

TL;DR - Can I filter the number of rows shown in a dataframe based on a value input by the user?

Thank you,

Hey @jareda,
Yes, you can filter a pandas dataframe based on some condition. Let us take your example i.e. you have two columns - Years and Amount. Now let’s say that a user inputs the years as: 2015, 2016, 2012, 2018.
What you can do is as follows:

# Make user's input as a list. Now it can be done in multiple ways. I am showing a simple example for now.
years_list = [2015, 2016, 2012, 2018] 
filtered_df = df[df['Years'].isin(years_list)] # This line will give only those rows where 'year' falls in years_list.
filtered_df.head() # Now you can see that filtered dataframe.

In a similar way, you can apply any filter. Now you can take input from the user and structure it in a proper format and then apply the technique shown above. Similarly, you can plot using filtered_df.plot().

I hope it helps!

For more info, you can check this out:

Best Wishes,

1 Like

Thank you so much for the quick response. How would I update the code you posted to instead of choosing each they would select the number of years? Lets say the years column has years 1-50. And I am asking the user to select a number via a streamlit slider to say 25 years. I would then want the dataframe to only show years 1-25.

Try it and let me know if it works.

import streamlit as st

num_yrs = st.slider('Select number of years', min_value=1, max_value=50) # Getting the input.
df = df[df['Years'] <= num_yrs] # Filtering the dataframe.
st.dataframe(df) # Displaying the dataframe.



Worked like a charm. Thank you.