get desired element in numpy array of unequal row lengths, without using for loop
<p>i have the below numpy array:</p>

<pre><code>array([['apple','banana','orange'],
   ['car','bike','train','ship','plane','scooter'],
   ['red','purple']], dtype=object)
</code></pre>

<p>the individual rows in the array are of unequal length, I want to get the last element of each row. I can get this by running a for loop but I guess there could be more direct way to doing so. The closest (wrong solution) i have is arr[:][-1] which gives me element of last row and arr[np.arange(len(arr)),-1] which throws an 'IndexError' error. </p>

<p>My desired output is:</p>

<pre><code>array([['orange','scooter','purple']], dtype=object)
</code></pre>

<p>I will appreciate any guidance. thank you.</p>

<p>Using loop comprehension : <code>np.array([i[-1] for i in arr],dtype=object)</code> might just be an efficient and fast way, specially if the lists are long enough. But since you are asking for a non-loopy solution, here's a way using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow"><code>np.concatenate</code></a> to get a flattened version and then indexing into it with proper indices for the selection of final elements of each list -</p>

<pre><code>np.concatenate(arr)[np.cumsum(map(len,arr))-1]
</code></pre>

<p>There's an use of <code>map</code> operator, which doesn't look like a vectorized operation, but since we are using it to only get the lengths of the lists, that part should not be heavy on runtime. So, I guess it's an almost vectorized approach.</p>

<p>Sample run -</p>

<pre><code>In [166]: arr
Out[166]: 
array([['apple', 'banana', 'orange'],
       ['car', 'bike', 'train', 'ship', 'plane', 'scooter'],
       ['red', 'purple']], dtype=object)

In [167]: np.concatenate(arr)[np.cumsum(map(len,arr))-1]
Out[167]: 
array(['orange', 'scooter', 'purple'], 
      dtype='|S7')
</code></pre>

<p>Please note that if we want an object dtype array, we would need to convert to such dtype before indexing : <code>np.concatenate(arr).astype(object)</code>.</p>

python arrays pandas numpy