簡體   English   中英

從Jupyter運行時,外部函數返回DataFrames,但不返回變量

[英]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)

右側返回一個結果元組,將其解壓縮為變量mydfFeb 然后可以像訪問其他任何變量一樣訪問這些變量。

等價於pd.DataFrame.pipe

mydf, Feb = mydf.pipe(testmath)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM