【问题标题】:Using interact from ipywidgets with a dataframe使用来自 ipywidgets 的交互与数据框
【发布时间】:2019-07-05 09:22:02
【问题描述】:

我是 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))

这成功地给了我想要的结果,这意味着我看到了数据框,并且Kosten A 列通过交互按钮进行了更改:

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

【问题讨论】:

    标签: python ipython ipywidgets


    【解决方案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))
    

    【讨论】:

    • 这使 df 被修改。 fixed 只是意味着,它“按原样”传递给交互函数。我会写一个不同的答案来处理 OP 的情况。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2017-02-28
      • 2021-10-19
      • 1970-01-01
      • 2010-11-12
      • 2017-09-03
      • 2020-04-16
      • 1970-01-01
      • 2022-11-29
      相关资源
      最近更新 更多