Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing numpy array with indicies

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
like image 824
Dave Avatar asked Dec 13 '25 14:12

Dave


1 Answers

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
like image 182
Marissa Novak Avatar answered Dec 15 '25 10:12

Marissa Novak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!