Pandas Dataframe to Code

前端 未结 3 1713
离开以前
离开以前 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 07:47

    I always used this code which help me much

    def gen_code(df):
        return 'pickle.loads({})'.format(pickle.dumps(df))
    
    import pickle
    code_string = gen_code(df)
    code_string
    

    So now you can copy the output of the code_string and paste it as follow to that string variable A

    A= 'Paste your code_string here'
    import pickle
    df=eval(A)
    

    This had helped me copy and past data frames in such platform

提交回复
热议问题