简体   繁体   中英

How do I select Pandas DataFrame with ipywidget?

I'm building an interactive function that can select inputs with a dropdown. Everything can be selected, except for an argument whose type is a pandas.DataFrame . How can I fix it?

Code I used

from ipywidgets import interact_manual
import pandas as pd
df_1 = pd.DataFrame(data=[[0, 1], [1, 2]], columns=["aaa", "bbb"])
df_2 = pd.DataFrame(data=[[8, 9], [7, 8]], columns=["xxx", "zzz"])
def display_df(df):
    return df
interact_manual(
    display_df,
    df=[("df_1", df_1), ("df_2", df_2)]
)

results:

BLAHBLAH
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
During handling of the above exception, another exception occurred:
BLAHBLAH
TraitError: Invalid selection: value not found

However, if I use the data inside only, the code works fine.

from ipywidgets import interact_manual
df_1 = [[0, 1], [1, 2]]
df_2 = [[8, 9], [7, 8]]
def display_df(df):
    return df
interact_manual(
    display_df,
    df=[("df_1", df_1), ("df_2", df_2)]
)

versions:

python== 3.7.3

ipykernel==5.1.1
ipython==7.6.1
ipython-genutils==0.2.0
ipywidgets==7.5.0

jupyter==1.0.0
jupyter-client==5.3.1
jupyter-console==6.0.0
jupyter-core==4.5.0
jupyter-kernel-gateway==2.4.0
jupyterlab==1.2.4
jupyterlab-code-formatter==1.0.3
jupyterlab-server==1.0.0

I think this has something to do with how ipywidgets and interact inspect the passed lists of objects. To avoid the issue, pass a simpler list of items, and then do the lookup in the interact function. Try this as an alternative:

import pandas as pd
import ipywidgets
from ipywidgets import interact_manual
df_1 = pd.DataFrame(data=[[0, 1], [1, 2]], columns=["aaa", "bbb"])
df_2 = pd.DataFrame(data=[[8, 9], [7, 8]], columns=["xxx", "zzz"])

opts = {
    'df_1': df_1,
    'df_2': df_2
}

def display_df(df_choice):
    print(opts[df_choice])

interact_manual(
    display_df,
    df_choice=opts.keys(),
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM