使用来自ipywidgets的interact与datafram

2024-09-30 06:33:52 发布

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

我不熟悉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

我做了以下几点:

^{pr2}$

这成功地给了我想要的结果,这意味着我看到了datframe,并且列Kosten A被交互按钮改变了: enter image description here

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


Tags: 数据函数df副本按钮interactipywidgetspr2
2条回答

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

^{pr2}$

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

   0
0  1
1  2
2  3

相关问题 更多 >

    热门问题