3

I would like to find a way to quickly manipulate an array of arrays in Numpy like this one, which has a shape of (10,):

[array([0, 1, 3]) ,array([0, 1, 7]), array([2]), array([0, 3]), array([4]),
 array([5]), array([6]) ,array([1, 7]), array([8]), array([9])]

For instance, I'd like to compute the total number of array elements, which is 16 for the array above, but without doing a for loop since in practice my "nested array" will be quite large.

Thanks!

3
  • 1
    Define "manipulation". If all you want is the length, it would be better to flatten into a single array. Otherwise your only choice s iteration because these arrays are uneven length. Commented Dec 31, 2018 at 7:58
  • 1
    That's a list of arrays - or object dtype array. Loops, list comprehensions are the normal tools. np.frompyfunc may be useful in some cases, with a modest speed difference. Commented Dec 31, 2018 at 8:04
  • As shown in the answer, 'flattening' the list into one array with concatenate way help. It depends on the manipulation. Commented Dec 31, 2018 at 16:57

1 Answer 1

5

One way to find the length of the array in your case is to ravel the nested numpy arrays and then find the length as below:

a = [array([0, 1, 3]) ,array([0, 1, 7]), array([2]), array([0, 3]), array([4]),
 array([5]), array([6]) ,array([1, 7]), array([8]), array([9])]

len(np.concatenate(a).ravel())
#Here we expand the numpy arrays and then flatten it to find the length.

Output:

16

As per my knowledge, ravel has a better timeit performance time in comparison to for loop.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think you need the ravel here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.