nusjjsun
nusjjsun

Reputation: 91

Quick ways to manipulate Numpy array in array

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!

Upvotes: 3

Views: 151

Answers (1)

Jim Todd
Jim Todd

Reputation: 1588

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.

Upvotes: 5

Related Questions