2016-07-29 53 views
1

我有一個帶有Python 3.5的Jupyter筆記本。我用它來分析模擬中的數據,我用Python編寫。無法在Jupyter中導入Python函數

在第一個單元格,我運行

%run control.py 

仿真和我得到的錯誤

> ImportError        Traceback (most recent call 
> last) ...\code\control.py in 
> <module>() 
>  15 from supplier import Supplier 
>  16 from heatmap import create_heatmaps 
> ---> 17 from write2csv import get_dataframe_from_results, write_raw_data_from_simulation, get_aggregated_lines_per_run 
>  18 #write_aggregated_results, 
>  19 
> 
> ImportError: cannot import name 'get_dataframe_from_results' 

我的程序在幾個文件分割。當我從導入中刪除方法'get_dataframe_from_results'時,它可以工作。此方法與其他幾個文件/模塊write2csv一起使用。

我不明白,爲什麼只有這種方法不能導入。該文件的所有其他功能都可以導入,所以我排除了源文件夾位置的問題。

函數本身不包含任何不尋常的:

def get_dataframe_from_results(all_aggr_results): 
    # convert results to pandas data frame from nested dictionary 
    results_df = pd.Panel(all_aggr_results) 
    STRATS = ("AN", "RE") 
    RLZ = ("NOR", "DIS") 
    vlzlist = [] 
    for vlz in sorted(all_aggr_results): 
     outerlist = [] 
     for rl in RLZ: 
      concatlist = [] 
      for strt in STRATS: 
       concatlist.append(pd.DataFrame.from_dict(results_df[vlz][strt][rl], orient="index")) 
      outerlist.append(pd.concat(concatlist, keys=STRATS)) 
     vlzlist.append(pd.concat(outerlist, keys=RLZ)) 
    results = pd.concat(vlzlist, keys=sorted(all_aggr_results)) 
    results.index.names = ["A", "B", "C", "C"] 
    results["totalcost"] = results["AAA"] + results["BBB"] + results["CCC"] + results["DDD"] 
    results.reset_index(inplace=True) # transform multiindex to columns 

    return results 

唯一的「理由」爲什麼它可能相對於其他功能很特別的是,它使用了大熊貓。

當我在PyCharm中運行腳本control.py時,它沒有問題。 當我在命令行中運行它,我得到

錯誤而「control.py」發現規範(: 模塊「控制」有沒有屬性「路徑」)

當我從我的代碼中刪除函數get_dataframe_from_results時,它在Jupyter中起作用。

我怎樣才能解決Jupyter中的這個錯誤並且具有我的功能?

筆記本電腦服務器的版本是4.1.0和運行:

的Python 2.7.11 |蟒蛇4.0.0(64位)| (默認情況下,2016年2月16日,9點58分36秒)[MSC v.1500 64位(AMD64)]

當前內核信息:

的Python 3.5.1 |阿納康達4.1.0(64位) | (默認,2016年6月15日,15:29:36)[MSC v.1900 64位(AMD64)]

回答

1

當您在開發Jupyter的同時開發(編輯)外部代碼時,會出現此問題筆記本。 Jupyter緩存防止它在第一次導入後重新加載外部文件。

解決方法是刪除外部python緩存目錄__pycache__,然後通過菜單項「Kernel - > Restart and Clear Output」重新啓動Jupyter筆記本。做這兩件事將強制Jupyter讀取外部文件的新/新副本,從而識別新的符號和其他修改。

(我知道你的問題是多一歲,但這個問題今天上午都掙扎後,我希望得到一個答案記錄出去別人誰運行到這一點。)