Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy select each row with different lengths

I have two array s

x=array([[0, 0, 0, 0, 0],
    [1, 0, 0, 0, 0],
    [2, 2, 2, 2, 2]])

I want to subselect elements in each row by the length in array y

y = array([3, 2, 4])

My target is z:

z = array([[0, 0, 0],
   [1, 0,],
   [2, 2, 2, 2]])

How could I do that with numpy functions instead of list/loop?

Thank you so much for your help.

like image 847
May Ju Avatar asked Feb 17 '26 04:02

May Ju


2 Answers

Numpy array is optimized for homogeneous array with a specific dimensions. I like to think of it like a matrix: it does not make sense to have a matrix with different number of elements on each rows.

That said, depending on how you want to use the processed array, you can simply make a list of array:

z = [array([0, 0, 0]),
array([1, 0,]),
array([2, 2, 2, 2]])]

Still, you will need to do that manually:

x = array([[0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [2, 2, 2, 2, 2]])
y = array([3, 2, 4])

z = [x_item[:y_item] for x_item, y_item in zip(x, y)]

The list comprehension iterates over the x and y combined with zip() to create the new slice of the original array.

like image 171
Tuwuh S Avatar answered Feb 19 '26 17:02

Tuwuh S


Something like this also,

z = [x[i,:e] for i,e in enumerate(y)]
like image 21
Vivek Harikrishnan Avatar answered Feb 19 '26 18:02

Vivek Harikrishnan



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!