1

我目前正在创建一个从熊猫继承 DataFrame 的类。我有兴趣开发一种名为“new_filter”的方法,它是 DataFrame 命令的更高级执行:

import pandas as pd
from ipywidgets import widgets
from IPython.display import display
import numpy as np

class Result(pd.DataFrame):

@property
def _constructor(self):
    return Result

def _filter_done(self, c):
    self._column_name = self._filter_dd.value
    self._expression = self._filter_txt.value
    return self[eval('self.'+ self._column_name +'  '+self._expression)]

def new_filter(self):
    self._filter_dd = widgets.Dropdown(options=list(self.columns),
                                            description='Column:')
    self._filter_txt = widgets.Text(description='Expr:')
    self._filter_button = widgets.Button(description = 'Done')
    self._filter_box = widgets.VBox([self._filter_dd, self._filter_txt, self._filter_button])
    display(self._filter_box)
    self._filter_button.on_click(self._filter_done)

创建对象后,如:

test = Result(np.random.randn(3,4), columns=['A','B','C','D']) #just an example
test_2 = test.new_filter()

然后,例如: 小部件输出

我想要的是“test_2”是“结果”类的一个对象。有什么解决办法吗?

4

1 回答 1

2

首先,您必须在函数中返回一些内容new_filter。其次,如果你想修改同一个对象,我觉得有点难。您可以做的一件事是拥有一个具有可以在_filter_done.

这是一个小例子,说明如何做到这一点:

import pandas as pd
from ipywidgets import widgets
from IPython.display import display
import numpy as np

class Result(pd.DataFrame):
    @property
    def _constructor(self):
        return Result

    def _filter_done(self, obj, c):
        ## obj is the obejct to be modified. 
        ## Updating its data attribute to have the filtered data.
        self._column_name = self._filter_dd.value
        self._expression = self._filter_txt.value
        obj.data = self[eval('self.'+ self._column_name +'  '+self._expression)]

    def new_filter(self):
        self._filter_dd = widgets.Dropdown(options=list(self.columns),
                                            description='Column:')
        self._filter_txt = widgets.Text(description='Expr:')
        self._filter_button = widgets.Button(description = 'Done')
        self._filter_box = widgets.VBox([self._filter_dd, self._filter_txt, self._filter_button])
        display(self._filter_box)

        result_obj = FilterResult()
        self._filter_button.on_click(lambda arg: self._filter_done(result_obj, arg))
        return result_obj

from traitlets import HasTraits
from traittypes import DataFrame

class FilterResult(HasTraits):
    data = DataFrame()

使用与您的问题相同的示例代码,即

test = Result(np.random.randn(3,4), columns=['A', 'B', 'C','D']) #just an example
test_2 = test.new_filter()

您可以看到,每当您单击完成时,更新dataframe的内容都在test_2.data.

于 2017-03-17T15:48:46.463 回答