Ipython选择控件-多重选择
这个内容是从一个网站上复制过来的,网址是:http://tooblippe.github.io/insightstack-blog/2014/04/24/pandas-pivot/
这里在问,怎么设置小部件的选择框,让用户可以同时选择多个选项呢?
%pylab inline
from pandas import Series, DataFrame, pivot_table
import numpy as np
import numpy
from IPython.html.widgets import interact, SelectWidget, CheckboxWidget, RadioButtonsWidget
from IPython.display import display
d = { 'Class' : Series( ['a', 'b', 'b','a','a', 'b', 'b','a','a', 'b', 'b','a','a','b','b','b']),
'Area' : Series( ['North','East', 'South', 'West','North','East', 'South', 'West','North','East', 'South', 'West','South', 'West','South', 'West']),
'Type' : Series( ['square', 'round','square', 'round', 'round', 'square', 'round', 'square', 'round', 'square','round', 'square',]),
'Web' : Series( ['Y','N','N','Y','Y','N','N','Y','Y','N','N','Y','Y','N','N','Y']),
'Agent' : Series( ['Mike', 'John', 'Pete','Mike', 'John', 'Pete','Mike', 'John', 'Pete','Mike', 'John', 'Pete','John', 'Pete','John', 'Pete']),
'Income' : Series( [20., 40., 90., 20.]),
'Profit' : Series( [1., 2., 3., 4.,1., 2., 3., 4.,1., 2., 3., 4.,1., 2., 3., 4.]),
'Stock' : Series( [20., 23., 33., 43.,12., 21., 310., 41.,11., 21., 31., 41.,11., 22., 34., 54.] )
}
df = DataFrame(d)
def my_pivot( rows, values, aggfunc):
dfp = df
piv = pivot_table( dfp, rows=rows, values=values, aggfunc=aggfunc)
print piv
i = interact( my_pivot,
rows = SelectWidget(values=list(df.columns)),
values = SelectWidget(values=['Profit', 'Stock']),
aggfunc = SelectWidget( values={ 'sum' : numpy.sum, 'ave' : numpy.average }))
1 个回答
5
你可以使用 'SelectMultiple' 小部件(IPython.html.widgets.SelectMultiple)。看起来这个功能是在你提问后才引入的(请记住,IPython 的 HTML 小部件可能会有一些不兼容的变化)。
这个小部件会给你和 'SelectWidget' 一样的列表,但用户可以选择多个选项。所有选中的选项会作为一个元组返回给你的交互回调。而且,自从你提问后,'values' 这个词已经改成 'options' 了。
下面的代码应该能满足你的需求。
i = interact( my_pivot,
rows = SelectMultiple(options=list(df.columns)),
values = SelectMultiple(options=['Profit', 'Stock']),
aggfunc = SelectMultiple(options={ 'sum' : numpy.sum, 'ave' : numpy.average }))
最后,你需要更新 'my_pivot' 函数,以确保它能正确处理现在作为元组传入的参数。