Reputation: 1137
I am using a dropdown widget for the values in one of the columns in my dataframe. Based on the value I choose in the dropdown, I want the dataframe to filter only those rows. I would then go on to use the filtered dataframe for my analysis.
col1 | col2 | col3
A | Orange | 2
B | Apple | 3
A | Apple | 4
I would have a dropdown (using ipywidgets) for col2 and when I choose Apple
, I want to get the resulting dataframe.
col1 | col2 | col3
B | Apple | 3
A | Apple | 4
Upvotes: 0
Views: 5371
Reputation: 302
This shows the fruit you select from the dropdown menu. I would advise you to watch the Scipy 2020 recoring on Interactive widgets if you want to learn more about widgets.
from ipywidgets import interact
import pandas as pd
def show_df(value):
data = [['A', 'Orange', 2],['B', 'Apple', 3],['A', 'Apple', 4]]
df = pd.DataFrame(data, columns=['Letter','Fruit','Number'])
print(df[df.Fruit==value])
interact(show_df, value = ['Apple','Orange'])
There are more dedicated ways to create a dropdown menu but this works. Such as in this example:
import ipywidgets as widgets
widgets.Select(
options=['Linux', 'Windows', 'OSX'],
value='OSX',
# rows=10,
description='OS:',
disabled=False
)
Upvotes: 2
Reputation: 118
I don't know about ipywidgets specifically but assuming you can get the value of your selection, say "Apple", filtering out by column values is quite easy.
df = pd.DataFrame({"col1": ["A", "B", "A"],
"col2": ["Orange", "Apple", "Apple"],
"col3": [2, 3, 4]})
df = df[df["col2"] == "Apple"]
Then, when you print df, you will get
col1 col2 col3
1 B Apple 3
2 A Apple 4
Basically you create a mask (a dataframe of True and False values) through df["col2"] == "Apple"
and then you can use that mask as an index to only get the values where the mask is True.
Upvotes: 0