idem
idem

Reputation: 155

Writing a 3D numpy array to files including its indices

I'm very new to this so apologies but hopefully I have the syntax right so you understand my question!
I have a numpy array with shape (2,2,2)

array([[[ 1, 1],
        [ 2, 2]],

       [[ 3, 3],
        [ 4, 4]]])

how do I write it to a file so it list the indices and the 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.

Upvotes: 0

Views: 234

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117856

You can use numpy.ndenumerate

a = np.array([[[1, 1],
               [2, 2]],

              [[3, 3],
               [4, 4]]])

for 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 the parentheses you 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 the file writing

with open('file.txt', 'w') as f:
    for indexes, value in np.ndenumerate(a):
        x,y,z = indexes
        f.write('{} {} {} {}\n'.format(x,y,z,value))

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

Not sure if this is the best way do this in NumPy, but you can do this using a combination of numpy.unravel_index, numpy.dstack and numpy.savetxt:

>>> arr = np.array([[[ 1, 1],
        [ 2, 2]],

       [[ 3, 3],
        [ 4, 4]]])
>>> a = np.dstack(np.unravel_index(np.arange(arr.size),
                                                   arr.shape) + (arr.ravel(),))
>>> np.savetxt('foo.txt', a[0,...], fmt='%d')
>>> !cat foo.txt
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

Upvotes: 0

Related Questions