python - Writing a 3D numpy array to files including its indices -
i'm new apologies have syntax right understand question!
have numpy array shape (2,2,2)
array([[[ 1, 1], [ 2, 2]], [[ 3, 3], [ 4, 4]]])
how write file list indices , array value i.e.
0 0 0 1 1 0 0 3 0 1 0 2 1 1 0 4 0 0 1 1 1 0 1 3 0 1 1 2 1 1 1 4
thanks, ingrid.
you can use numpy.ndenumerate
a = np.array([[[1, 1], [2, 2]], [[3, 3], [4, 4]]]) items in np.ndenumerate(a): print(items)
output
((0, 0, 0), 1) ((0, 0, 1), 1) ((0, 1, 0), 2) ((0, 1, 1), 2) ((1, 0, 0), 3) ((1, 0, 1), 3) ((1, 1, 0), 4) ((1, 1, 1), 4)
to remove parentheses can unpack everything
for indexes, value in np.ndenumerate(a): x,y,z = indexes print(x,y,z,value)
output
0 0 0 1 0 0 1 1 0 1 0 2 0 1 1 2 1 0 0 3 1 0 1 3 1 1 0 4 1 1 1 4
to handle file writing
with open('file.txt', 'w') f: indexes, value in np.ndenumerate(a): x,y,z = indexes f.write('{} {} {} {}\n'.format(x,y,z,value))
Comments
Post a Comment