Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 647
Manoj Agrawal Avatar asked Aug 08 '17 23:08

Manoj Agrawal


1 Answers

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
like image 177
OLIVER.KOO Avatar answered Sep 19 '22 06:09

OLIVER.KOO