Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe to Code

Tags:

python

pandas

If I have an existing pandas dataframe, is there a way to generate the python code, which when executed in another python script, will reproduce that dataframe.

e.g.

In[1]: df  Out[1]:    income   user 0   40000    Bob 1   50000   Jane 2   42000  Alice  In[2]: someFunToWriteDfCode(df)  Out[2]:  df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],      ...:                    'income': [40000, 50000, 42000]}) 
like image 971
agf1997 Avatar asked Jan 20 '17 18:01

agf1997


People also ask

What will be the syntax for pandas DataFrame?

data takes various forms like ndarray, series, map, lists, dict, constants and also another DataFrame. For the row labels, the Index to be used for the resulting frame is Optional Default np. arange(n) if no index is passed. For column labels, the optional default syntax is - np.

How do you convert a DataFrame into a data type?

to_numeric() The best way to convert one or more columns of a DataFrame to numeric values is to use pandas. to_numeric() . This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.

What is a pandas DataFrame?

What is a DataFrame? A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with rows and columns.


1 Answers

You could try to use the to_dict() method on DataFrame:

print "df = pd.DataFrame( %s )" % (str(df.to_dict())) 

If your data contains NaN's, you'll have to replace them with float('nan'):

print "df = pd.DataFrame( %s )" % (str(df.to_dict()).replace(" nan"," float('nan')")) 
like image 93
madoki Avatar answered Sep 20 '22 00:09

madoki