Search code examples
python-3.xfunctiondataframereturn

Returning a dataframe in python function


I am trying to create and return a data frame from a Python function

def create_df():
    data = {'state': ['Ohio','Ohio','Ohio','Nevada','Nevada'],
           'year': [2000,2001,2002,2001,2002],
           'pop': [1.5,1.7,3.6,2.4,2.9]}
    df = pd.DataFrame(data)
    return df
create_df()
df

I get an error that saying that df is not defined. If I replace return with print I get print of the data frame correctly. Is there a way to do this?


Solution

  • Wwhen you call create_df(), Python calls the function but doesn't save the result in any variable. That is why you got the error.

    Assign the result of create_df() to a new variable df like this:

    df = create_df()
    df