SimpleJSON and NumPy array

后端 未结 9 1380
挽巷
挽巷 2020-12-04 10:56

What is the most efficient way of serializing a numpy array using simplejson?

9条回答
  •  Happy的楠姐
    2020-12-04 11:42

    If you want to apply Russ's method to n-dimensional numpy arrays you can try this

    class NumpyAwareJSONEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, numpy.ndarray):
                if obj.ndim == 1:
                    return obj.tolist()
                else:
                    return [self.default(obj[i]) for i in range(obj.shape[0])]
            return json.JSONEncoder.default(self, obj)
    

    This will simply turn a n-dimensional array into a list of lists with depth "n". To cast such lists back into a numpy array, my_nparray = numpy.array(my_list) will work regardless of the list "depth".

提交回复
热议问题