Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.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 从Jupyter运行时,外部函数返回数据帧,但不返回变量_Python_Pandas_Jupyter Notebook - Fatal编程技术网

Python 从Jupyter运行时,外部函数返回数据帧,但不返回变量

Python 从Jupyter运行时,外部函数返回数据帧,但不返回变量,python,pandas,jupyter-notebook,Python,Pandas,Jupyter Notebook,假设您在一个名为MainNotebook.ipynb的Jupyter笔记本中有一个数据帧,并且您正在将该数据帧传递给一个名为testmath的python文件中名为testmath.py的外部python函数: import pandas as pd from testmath import testmath sales = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140}, {'account': '

假设您在一个名为MainNotebook.ipynb的Jupyter笔记本中有一个数据帧,并且您正在将该数据帧传递给一个名为
testmath
的python文件中名为
testmath.py
的外部python函数:

import pandas as pd
from testmath import testmath

sales = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
         {'account': 'Alpha Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},
         {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]

mydf = pd.DataFrame(sales)

testmath(mydf)
下面是testmath.py的代码:

import pandas as pd

def testmath(inputdf):
    Feb = inputdf['Feb']
    inputdf['FebPesos'] = Feb * 12
    return inputdf, Feb
我试图让函数返回数据帧
mydf
和变量
Feb
,以便在以后的分析中使用它们

然而,奇怪的是,当您从
MainNotebook.ipynb
运行
testmath(mydf)
时,当返回数据帧并添加新列时,无法访问变量'Feb'

我的意思是,如果您从MainNotebook运行以下操作:

from importdebug import testmath
import pandas as pd

sales = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
         {'account': 'Alpha Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},
         {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 }]

mydf = pd.DataFrame(sales)

testmath(mydf)

print(Feb)
打印(Feb)命令返回错误: 名称错误:未定义名称“Feb”

有没有办法检索函数内部生成的变量?特别是如果你有很多的话?(我更喜欢不涉及全局变量的方法,gulp)


我已经尝试删除pycache,重新启动内核并清除输出。我还更新了所有的conda软件包,但仍然不走运。

由于您的函数返回一个
元组,您可以使用:

右侧返回一个结果元组,这些结果被解包为变量
mydf
Feb
。然后可以像访问任何其他变量一样访问这些变量

等效地,具有:


为什么你不能引用它?根据我的经验,这很好。可以发布错误消息吗?只是添加了错误文本。您输入到
getmydata
的变量是
myjsonfile
,但在内部,您从名为
inputpath
的变量中读取(我假设该变量在笔记本中的某个地方定义)。这可能就是为什么在外部调用函数时找不到数据帧,因此没有名称“apples”。介意用不同的变量进行双重检查吗?即使对Jupyter中的熊猫(和一些笔记本电脑)来说可能有点困难,请尝试提供一个答案,以便我们知道要解决什么错误。
mydf, Feb = testmath(mydf)
mydf, Feb = mydf.pipe(testmath)