簡體   English   中英

如何將 pandas dataframe output 從 ZC1C425268E68385D1AB5074FZ9 保存到工作區C17A

[英]How to save pandas dataframe output from function to workspace?

I have the following simple function importing file from csv and I would like to store the resulting dataframe to the Python worskpace. 實際上,創建的 DF 應該用作我的代碼的另一個函數的輸入。

我試圖將 dataframe 聲明為全局,但它仍然不“可見”

def tabpol(annee):

    # Import de la table polices
    import pandas as pd
    global table_polices
    
    pd.options.mode.chained_assignment = None
    libtab="C:/Users/a61787/Documents/NBV/NBV_2020/Modele/Table_"+str(annee)+"/"
        
    table_polices=pd.read_csv(libtab+'pol.csv')
    return table_polices

您可以得到的任何幫助將不勝感激謝謝

=> 你說得對,我需要刪除返回參數。 這樣做,我有我想要的直接使用 function

但實際上,這個 function 存儲在一個名為“NBV”的模塊中,當我從模塊調用 function 時,dataframe 不可見

from NBV import tabpol
tabpol(2019)
print(table_polices)

NameError:名稱'table_polices'未定義

因此,在 Python 中,全局變量僅在它們定義的模塊內可見,而不在 Python 應用程序的所有模塊中可見。

更准確地說,function tabpol()定義在一個名為NBV的模塊中,該模塊還創建了一個全局變量table_polices 后者將在整個模塊中可見(即使在 function tabpol()) ,但在此模塊之外不可見。 這就是您收到NameError: name 'table_polices' is not defined


有多種解決方法,但建議其中一種是有風險的,因為這在很大程度上取決於您的應用程序的設計。 只是舉個例子,這是一種可以解決問題的替代方法:

# NBV.py
import pandas as pd


table_polices_2019 = tabpol(2019)


def tabpol(annee):
    pd.options.mode.chained_assignment = None
    libtab="C:/Users/a61787/Documents/NBV/NBV_2020/Modele/Table_"+str(annee)+"/"
    df = pd.read_csv(libtab+'pol.csv')
    
    return df

您可以使用NBV.table_polices_2019 table_polices_2019

但是,這對我來說聽起來不太對勁。 我也不確定全局變量是否會改進當前的設計,但我不這么認為。 I understand that you don't want to create a pandas dataframe from the fixed csv file over and over again but turning this pandas dataframe into a global variable doesn't sound like a good solution to me (unless I am missing anything here)

暫無
暫無

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

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