Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 508
nusjjsun Avatar asked Sep 09 '26 00:09

nusjjsun


1 Answers

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.

like image 168
Jim Todd Avatar answered Sep 11 '26 15:09

Jim Todd



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!