首页 > 解决方案 > 如何使用 ipywidget 选择 Pandas DataFrame?

问题描述

我正在构建一个交互式功能,可以通过下拉菜单选择输入。可以选择所有内容,除了类型为 a 的参数pandas.DataFrame。我该如何解决?

我使用的代码

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)]
)

结果:

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

但是,如果我只使用里面的数据,代码就可以正常工作。

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)]
)

版本:

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

标签: pythonpandasjupyter-notebookipywidgets

解决方案


我认为这与 ipywidgets 和交互检查传递的对象列表的方式有关。为了避免这个问题,传递一个更简单的项目列表,然后在交互函数中进行查找。试试这个作为替代方案:

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(),
)

推荐阅读