Update pandas dataframe based on a selected value from a widget

The following example works fine to filter and display the dataframe df. However, what I want to do is NOT to display the filtered dataframe. I want to store the filtered dataframe into a new dataframe and use it for the subsequent operations.

For example, is it possible to display only the Select widget and filter the dataframe in the background without displaying it?


# Dataframe
df = pd.DataFrame({
    'CcyPair':['EUR/USD', 'AUD/USD' ,'USD/JPY'], 
    'Requester':['Client1', 'Client2' ,'Client3'],
    'Provider':['LP1', 'LP2' ,'LP3']
})
dfx = df.copy()

# Dropdown
providers = list(df.Provider.unique())
select_widget = pn.widgets.Select(options=providers)

# Query dataframe based on value in Provider dropdown
@pn.depends(select_widget)
def query(x):
    filtered_df = df[df.Provider==x]
    dfx = filtered_df
    return filtered_df
        
# Display Output

pn.Column(select_widget, query)

When I print dfx in the next cell, it prints the entire dataframe. I appreciate any help.

1 Like

Hi @erkaner,

I think this might be what your looking for at least one method making use of panel bind, if you search for @riziles whom has provided some good alternatives to this utilising param but the below code is what I can recall from top of my head. Hope of some help

import panel as pn
import pandas as pd

pn.extension()

# Dataframe
df = pd.DataFrame({
    'CcyPair':['EUR/USD', 'AUD/USD' ,'USD/JPY'], 
    'Requester':['Client1', 'Client2' ,'Client3'],
    'Provider':['LP1', 'LP2' ,'LP3']
})
dfx = df.copy()

# Dropdown
providers = list(df.Provider.unique())
select_widget = pn.widgets.Select(options=providers)

# Query dataframe based on value in Provider dropdown
@pn.depends(select_widget)
def query(x):
    filtered_df = df[df.Provider==x]
    return filtered_df

get_dataframe = pn.bind(query, select_widget)
      
# Display Output

pn.Column(select_widget)

And then you can in another jupyter cell run something like to grab the filtered dataframe

filtered_df = get_dataframe()
filtered_df
2 Likes