pass data frame from one function to another in python
Question: I am using two functions, one to load data and another to get a summary of the
same data. However in second function analyze() I get the error df not
defined. How do I pass df from loader() to analyze() ?

    
    
    from xlwings import Workbook, Range
    import pandas as pd
    
    def Loader():   
            wb = Workbook.caller() 
            file_path = Range(1,(1,1)).value
            file=pd.read_excel(file_path, sheetname='Sheet1')
            df = pd.DataFrame(file)    
    
    def analyze():
            Range('C1').value=df.describe() 
    


Answer: With several ways depending on what you want to do. The simplest way is to
`return` the `df` from the `Loader()` and then give it to the `analyze()` as
an argument:

    
    
    def Loader():   
        wb = Workbook.caller() 
        file_path = Range(1,(1,1)).value
        file=pd.read_excel(file_path, sheetname='Sheet1')
        df = pd.DataFrame(file)
        return df
    
    def analyze(df):
        Range('C1').value=df.describe()
    
    # Use it this way
    dataFrame = Loader()
    analyze(dataframe)
    

Then another way is to have a Loader class like this:

    
    
    class Loader(object):
        def __init__(self):
            wb = Workbook.caller() 
            file_path = Range(1,(1,1)).value
            file=pd.read_excel(file_path, sheetname='Sheet1')
            self.df = pd.DataFrame(file)
    
            # 1) If you want to analyse when you create the object
            # call analyze() here
            self.analyze()
    
        def analyze(self):
            Range('C1').value=self.df.describe()
    
        loader = Loader()
        # 2) Otherwise you can keep control of analyze()
        # and call it whenever you want, like this:
        loader.analyze()
    

Of course there are other ways too (like having a global variable for the df).

