简体   繁体   中英

Store dataframe in variable python

I'm still learning python and I have a simple problem and i made a reasearch already with no success.

I have this simple code:

import pandas as pd


def readDF():
  df = **reads  a df from excel**
  return df

DF = readDF()

The problem is that everytime i try to access the DF variable from another module it reads the entire datafram again, and I just want to read it one time and "store it" for use. Is there any way to read it just the first time and "store it" in the variable DF?

You could load the data into a data-storage class which calls the function once, or doesn't use a function at all:

import pandas as pd

# Option 1: call function
class DataStorage:
    def __init__(self):

    self.df = self.readDF()        

    def readDF(self):
         df = pd.read_excel('test.xlsx')
        return df

# Option 2: as attribute:
class DataStorage:
    def __init__(self):
        
        self.df = pd.read_excel('test.xlsx')

To access the data in either option, you would have in your calling module:

from data_module import DataStorage

data = DataStorage()
data.df  # your dataframe


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM