0

I have created a 2D 10x10 Array. using Numpy I want to iterate over the array as efficiently as possible.

However I would like to return the array values. essentially iterating over the 10x10 array 10 times and return a 1x10 array each time.

 import datetime
 import numpy as np
 import random

 start = datetime.datetime.now()
 a = np.random.uniform(low=-1, high=1, size=(10,10))
 print("Time :",datetime.datetime.now() - start)

 for x in np.nditer(a):
    print(x)

the result is as follows:

0.5738994777717537
0.24988408410910767
0.8391827831682657
0.0015975845830569213
0.54477459840569
0.14091622639476165
-0.36517132895234106
-0.06311125453484467
-0.6572544506539948

...

100 times

However I would expect the result to be:

[0.5738994777717537,
0.24988408410910767,
0.8391827831682657,
0.0015975845830569213,
0.54477459840569,
0.14091622639476165,
-0.36517132895234106,
-0.06311125453484467,
-0.6572544506539948],[...]

...

10 times

Any help would be appreciated!

  • First, why are you using nditer? What documentation are you working from? Why not just x.tolist()? Or for x in a: print(x)? nditer effectively flattens the array, providing each value without regard to the row/column structure. That should be obvious from the nditer documentation. Also nditer, at least when called from Python, is not a speed tool. It is not faster than simple iteration. – hpaulj Aug 19 at 18:18
  • Efficient and iterate don't belong together when talking about numpy arrays. Focus on using the fast compiled whole-array methods, not iteration. – hpaulj Aug 19 at 18:26
  • You are just interested in slicing. Don't try to iterate, just have a look at numpy slicing. You are just looking for a[0], a[1] etc. – pythonic833 Aug 19 at 18:46
1

To directly answer your question, this does exactly what you want:

import numpy as np
a = np.random.uniform(low=-1, high=1, size=(10,10))
print(','.join([str(list(x)) for x in a]))

This will print

[-0.2403881196886386, ... , 0.8518165986395723],[-0.2403881196886386, ... , 0.8518165986395723], ..., [-0.2403881196886386, ... , 0.8518165986395723]

The reason you're printing just the elements of the array is due to the way nditer works. nditer iterates over single elements, even at a multidimensional level, whereas you want to iterate over just the first dimension of the array. For that, for x in a: works as intended.

Edit

Here is a good link if you want to read up on how nditer works: https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#arrays-nditer

  • That indexing reference is not very useful unless you read all the way to end, and start working in cython. – hpaulj Aug 19 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.