Python's equivalent for R's dput() function

后端 未结 4 1768
遇见更好的自我
遇见更好的自我 2020-12-20 11:16

Is there any function in python similar to dput() function in R?

4条回答
  •  庸人自扰
    2020-12-20 11:42

    This answer focuses on json.dump() and json.dumps() and how to use them with numpy arrays. If you try, Python will hit you with an error saying that ndarrays are not JSON serializable:

    import numpy as np
    import json
    
    a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    json.dumps(a)
    
    TypeError: Object of type 'ndarray' is not JSON serializable
    

    You can avoid this by translating it to a list first. See below for two working examples:

    json.dumps()

    json.dumps() seems to be the closest to R's dput() since it allows you to copy-paste the result straight from the console:

    json.dumps(a.tolist()) # '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'
    

    json.dump()

    json.dump() is not the same as dput() but it's still very useful. json.dump() will encode your object to a json file.

    # Encode:
    savehere = open('file_location.json', 'w')
    json.dump(a.tolist(), savehere)
    

    which you can then decode elsewhere:

    # Decode:
    b = open('file_location.json', 'r').read()   # b is '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'
    c = json.loads(b)
    

    Then you can transform it back a numpy array again:

    c = np.array(c)
    

    More information

    on avoiding the 'not serializable' error see:

    • numpy array is not json serializable

    • how to make classes json serializable (kind of unrelated, but very interesting)

提交回复
热议问题