python - 如何使用 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
解决方案
我认为这与 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(),
)
推荐阅读
- r - R Highcharter:具有多个系列的多级钻取
- sql - 将日期序列调用到存储过程的最佳方法
- scala - 而不是使用两种看起来完全相同的方法,我如何提取泛型参数(一个是 List[T],另一个是泛型 T)
- angular - 如何以角度编写我的函数的文档
- reporting-services - 显示所有员工,即使为零或为空
- google-sheets - 我想在 Google 电子表格中导入实时足球比分
- javascript - 如何获取布尔值,如果单击元素 id - Angular
- android - Android gradle构建错误:底部边框上的填充部分太多
- arrays - 如何使用 jmeter 中的 JSON Extractor 从数组中提取值?
- php - 如何从这个多维关联数组中单独提取这个键