Reputation: 37
The following code will print the values in a numpy array preceeded by array indices.
import numpy as np
a = np.np.arange(6).reshape(2,3)
for index, val in np.ndenumerate(a):
print(index, val)
It will print the following:
(0,0) 0
(0,1) 1
(0,2) 2
(1,0) 3
(1,1) 4
(1,2) 5
Is there a way to extract out the index values so each value can be printed separated by a comma similar to this?
0,0,0
0,1,1
0,2,2
1,0,3
1,1,4
1,2,5
Upvotes: 3
Views: 4553
Reputation: 377
import numpy as np
a = np.arange(6).reshape(2,3)
for index, val in np.ndenumerate(a):
print(index[0], index[1], val)
This worked for me. You might want to do the print part dynamically if the array will change sizes, but if it's a one off piece of code I think this is fine.
Upvotes: 0
Reputation: 554
To access the values in your tuple index
, use their indices. And you can use string formatting to print the string how you want. See this for more information:
https://pyformat.info/
You could do the printing like this:
>>> for index, val in np.ndenumerate(a):
... print '{}, {}, {}'.format(index[0], index[1], val)
...
0, 0, 0
0, 1, 1
0, 2, 2
1, 0, 3
1, 1, 4
1, 2, 5
Upvotes: 2