Ipython Select Widget多个选择

2024-04-29 07:39:55 发布

您现在位置:Python中文网/ 问答频道 /正文

从以下位置复制示例:http://tooblippe.github.io/insightstack-blog/2014/04/24/pandas-pivot/

如何配置widget选择框以允许同时进行多个选择?在

%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 }))

Tags: importnumpyjohnrowsseriespivotmikevalues
1条回答
网友
1楼 · 发布于 2024-04-29 07:39:55

您可以使用“SelectMultiple”小部件(IPython.html.widgets。选择多个)。看起来这是在您发布问题之后引入的(请记住,ipythonhtml小部件仍然会受到API破坏性更改的影响)。在

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

下面的代码应该做你想做的。在

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'u pivot'函数,以确保它正确处理现在作为元组接收的参数。在

相关问题 更多 >