Pandas Dataframe to Code

前端 未结 3 1785
离开以前
离开以前 2021-02-12 07:37

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.

3条回答
  •  没有蜡笔的小新
    2021-02-12 08:06

    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')"))
    

提交回复
热议问题