Use Holoviz Panel Dropdown value to query dataframe

1.1k views Asked by At

I am trying to use a Holoviz Panel dropdown widget value to query a dataframe. The dataframe however does not reflect the change in the dropdown value. I added a markdown widget to check if the change in the dropdown value is being captured - It seems to be. However, I can't figure out how to update the dataframe. I am a complete beginner to programming, just trying to learn. Any help is appreciated.

import pandas as pd
import panel as pn
pn.extension()

# Dataframe

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

# Dropdown

a2 = pn.widgets.Select(options=list(df.Provider.unique()))

# Query dataframe based on value in Provider dropdown

def query(x=a2):
    y = pn.widgets.DataFrame(df[(df.Provider==x)])
    return y

# Test Markdown Panel to check if the dropdown change returns value

s = pn.pane.Markdown(object='')

# Register watcher and define callback

w = a2.param.watch(callback, ['value'], onlychanged=False)

def callback(*events):
    print(events)
    for event in events:
        if event.name == 'value':
            df1 = query(event.new)
            s.object = event.new

# Display Output

pn.Column(query, s)

Output Image

2

There are 2 answers

0
sri40 On

Figured it out, turned out I just needed to add @pn.depends above my query function. Once I added pn.depends(a2, watch=True), the dataframe was filtered based on a2 input. The callback and watcher were unnecessary.

0
Matthew Walker On

Inspired by the self-answer, the following code produces a select box containing the list of providers and a dataframe filtered on that selection. It was tested on Panel version 0.13.1.

Screenshot of Panel output

Note that the watch=True suggestion in the self-answer wasn't necessary.

import pandas as pd
import panel as pn
pn.extension()

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

# 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 = pn.widgets.DataFrame(df[df.Provider==x])
    return filtered_df
        
# Display Output
pn.Column(select_widget, query)