Save and Read a Python Dictionary to/from CSV -
i want perform simple operation, store python dictionary csv file , later read file dictionary.
my dictionary maps string list of numpy arrays, example:
d = {'x': [array([2, 3, 4]), array([5, 6, 7])], 'y': [array([1, 2, 3]), array([4, 5, 6])] so store dictionary csv , recreate dictionary file in different program.
i've tried using python's csv module write dictionary csv file had trouble storing list of multidimensional numpy arrays properly. when used module read read blank rows in csv file.
i tried use pandas, wasn't able figure out how use read_csv() method read list of numpy arrays dictionary.
in [610]: d = {'x': [np.array([2, 3, 4]), np.array([5, 6, 7])], 'y': [np.array( ...: [1, 2, 3]), np.array([4, 5, 6])]} in [611]: d out[611]: {'x': [array([2, 3, 4]), array([5, 6, 7])], 'y': [array([1, 2, 3]), array([4, 5, 6])]} in [613]: np.save('test.npy',d) in [614]: np.load('test.npy') out[614]: array({'x': [array([2, 3, 4]), array([5, 6, 7])], 'y': [array([1, 2, 3]), array([4, 5, 6])]}, dtype=object) so calling save on dictionary, wraps dictionary in object type array, , saves that. , elements of object array saved respective pickle method. pickles dictionary, , lists within dictionary. arrays within lists pickled version of np.save. lots of nesting. works.
and item can used pull dictionary out of object array:
in [616]: dd=np.load('test.npy').item() in [617]: dd out[617]: {'x': [array([2, 3, 4]), array([5, 6, 7])], 'y': [array([1, 2, 3]), array([4, 5, 6])]} and using pickle directly:
in [626]: pickle.dump(d, open('test.pkl','wb')) in [627]: np.load('test.pkl') out[627]: {'x': [array([2, 3, 4]), array([5, 6, 7])], 'y': [array([1, 2, 3]), array([4, 5, 6])]} in [629]: pickle.load(open('test.pkl','rb')) out[629]: {'x': [array([2, 3, 4]), array([5, 6, 7])], 'y': [array([1, 2, 3]), array([4, 5, 6])]} to write csv dictionary i'd create structured array fields named 'x' , 'y'. think i'd have concatenate arrays, can produce 1d array. csv like:
x y 2 1 3 4 .... or if subarrays same length might able produce
x y 2 5 1 4 3 6 2 5 ... in if still want go csv route, need decide how represent values simple lines of columns.
Comments
Post a Comment