将来自ipywidgets的交互与数据框一起使用

时间:2019-07-05 09:22:02

标签: python ipython ipywidgets

我是ipywidgets的新手,正在尝试结合使用此库中的interact和数据框。我的数据框是:

df
KundenNR    Kundengruppe    Wertpapierart   Erlös   Kosten A    Kosten B
1   1   A   100     30  10
1   1   B   200     30  15
1   1   C   300     30  20

到目前为止,我已执行以下操作:

from ipywidgets import widgets, interact, interactive, fixed, interact_manual
from IPython.display import display
def f(x):
    df1 = df.copy()
    df1['Kosten A'] = x
    y = x*x
    print(df1, y)

interact(f, x=(10,50,5))

这成功地给了我所需的结果,这意味着我看到了datframe,并且Kosten A列已通过交互按钮进行了更改: enter image description here

我真的很想知道如何将数据框直接传递给函数,而不是从中创建一个副本。有解决方案吗?

2 个答案:

答案 0 :(得分:1)

将数据框作为参数传递给用fixed包装的函数。之后,您应该能够调用数据框,并且由于交互而引起的任何更改都应该是永久的。

    import pandas as pd
    from ipywidgets import widgets, interact, interactive, fixed, interact_manual
    from IPython.display import display

    df = pd.DataFrame([1,2,3])

    def f(x, df):
        df
        df['Kosten A'] = x
        y = x*x
        print(df, y)

    interact(f, x=(10,50,5), df = fixed(df))

答案 1 :(得分:0)

使用fixed伪部件是一种将额外的参数传递给交互函数的方法,这些参数不会显示为小部件。参见:https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html#Fixing-arguments-using-fixed

但是,fixed的实现非常简单(interaction.py):

from traitlets import HasTraits, Any, Unicode

class fixed(HasTraits):
    """A pseudo-widget whose value is fixed and never synced to the client."""
    value = Any(help="Any Python object")
    description = Unicode('', help="Any Python object")
    def __init__(self, value, **kwargs):
        super(fixed, self).__init__(value=value, **kwargs)
    def get_interact_value(self):
        """Return the value for this widget which should be passed to
        interactive functions. Custom widgets can change this method
        to process the raw value ``self.value``.
        """
        return self.value

因此,您可以编写自己的伪部件fixed_copy

import pandas as pd
from ipywidgets import interact, fixed

df = pd.DataFrame([1,2,3])

class fixed_copy(fixed):
    def get_interact_value(self):
        return self.value.copy()

@interact(x=(10, 50, 5), df=fixed_copy(df))
def f(x, df):
    df['Kosten A'] = x
    y = x*x
    return (df, y)

它很好地显示了修改后的df,但是之后,df的值仍然是:

   0
0  1
1  2
2  3