[英]One of my pygame screens is running 2 times when I import a function that returns 2 variables from another file
[英]External function returns DataFrames but not variables when running from Jupyter
假設您在Jupyter筆記本中有一個名為MainNotebook.ipynb的數據框,並且正在將該數據框傳遞給名為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
我正在嘗試讓該函數同時返回DataFrame mydf
和變量Feb
以便可以將它們用於以后的分析。
但是,奇怪的是,當您從MainNotebook.ipynb
運行testmath(mydf)
時,雖然DataFrame返回並添加了新列,但無法訪問變量'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)
要print(Feb)
的命令print(Feb)
返回錯誤:NameError:未定義名稱'Feb'
有什么方法可以檢索函數內部生成的變量? 特別是如果您有很多呢? (我更喜歡不涉及全局變量的方法,gulp)
我已經嘗試刪除pycache,然后重新啟動內核並清除輸出。 我還更新了所有的conda程序包,但仍然沒有運氣。
由於函數返回一個tuple
,因此可以使用序列解壓縮 :
mydf, Feb = testmath(mydf)
右側返回一個結果元組,將其解壓縮為變量mydf
和Feb
然后可以像訪問其他任何變量一樣訪問這些變量。
等價於pd.DataFrame.pipe
:
mydf, Feb = mydf.pipe(testmath)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.