0

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?

  • Could you share your full code to tested? – Alberto Castillo Sep 23 '20 at 21:07
  • Please, remove salutations. [Should 'Hi', 'thanks', taglines, and salutations be removed from posts?](https://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts) – maciejwww Sep 24 '20 at 09:52

1 Answers1

0

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


Joseph
  • 578
  • 3
  • 15
  • Thanks, I used this with the global statement and it did it work. – Valentín De La Rosa Sep 24 '20 at 16:28
  • It should also work without a global (its good to avoid these if you can: https://stackoverflow.com/questions/19158339/why-are-global-variables-evil/19158418#19158418). At this stage it might be alright but as your application grows could cause problems. If you want to remove it now, feel free to post an edit to your original post and I can help troubleshoot why it is only working with the global. – Joseph Sep 24 '20 at 16:32