【问题标题】:Ipython Select Widget- more than one selectionIpython Select Widget - 多个选择
【发布时间】:2014-08-28 10:32:05
【问题描述】:

复制示例来自: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 }))

【问题讨论】:

    标签: python pandas ipython ipython-notebook


    【解决方案1】:

    您可以使用“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 }))
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多