Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用数据帧从ipywidgets进行交互_Python_Ipython_Ipywidgets - Fatal编程技术网

Python 使用数据帧从ipywidgets进行交互

Python 使用数据帧从ipywidgets进行交互,python,ipython,ipywidgets,Python,Ipython,Ipywidgets,我不熟悉ipywidgets,尝试将此库中的交互与数据帧结合使用。我的数据帧是: 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,

我不熟悉
ipywidgets
,尝试将此库中的
交互
与数据帧结合使用。我的数据帧是:

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
包装的函数。您应该能够在之后调用您的数据帧,并且由于您的交互而引起的任何更改都应该是永久性的

将熊猫作为pd导入
从ipywidgets导入小部件,交互,交互,固定,交互
从IPython.display导入显示
df=pd.DataFrame([1,2,3])
def f(x,df):
df
df['Kosten A']=x
y=x*x
打印(df,y)
相互作用(f,x=(10,50,5),df=固定(df))

使用
固定的
伪小部件是一种向交互函数传递额外参数的方法,这些参数不会显示为小部件。见:

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

因此,您可以编写自己的伪小部件,
fixed\u copy

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

这使得df被修改
fixed
的意思是,它按原样传递给交互函数。我会写一个不同的答案来处理OP的案子。