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

Using interact from ipywidgets with a dataframe

我是 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 被交互按钮改变了:

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

将数据帧作为参数传递给用 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))

使用 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