Ipython Select Widget-多选

Dat*_*ede 4 python ipython pandas jupyter-notebook

从以下位置复制示例: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 }))
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以使用“SelectMultiple”小部件 (IPython.html.widgets.SelectMultiple)。看起来这是在您发布问题后引入的(请记住,IPython HTML 小部件仍然受到 API 重大更改的影响)。

这将为您提供与“SelectWidget”相同的列表,但允许用户进行多项选择。所有选定的选项都将作为元组发送回您的交互回调。另外,自从您发布后,此“值”已更改为“选项”。

下面的代码应该可以完成您想要的操作。

i = interact( my_pivot,
             rows    = SelectMultiple(options=list(df.columns)), 
             values  = SelectMultiple(options=['Profit', 'Stock']),
             aggfunc = SelectMultiple(options={ 'sum' : numpy.sum, 'ave' : numpy.average }))
Run Code Online (Sandbox Code Playgroud)

最后,您需要更新“my_pivot”函数,以确保它正确处理现在作为元组接收的参数。