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>Use a list of list if the fastest:</p>

<pre><code>import numpy as np
import random

items = ['apple','banana','orange', 'car','bike','train','ship','plane','scooter', 'red','purple']
a = [random.sample(items, random.randint(2, 10)) for _ in range(1000)]
b = np.array(a)

%timeit [x[-1] for x in a] # 62.1 Âµs
%timeit [x[-1] for x in b] # 75.9 Âµs
f = np.frompyfunc(lambda x:x[-1], 1, 1)
%timeit f(b)  # 165 Âµs

import cytoolz
%timeit list(cytoolz.pluck(-1, a)) # 42.7 Âµs
%timeit list(cytoolz.pluck(-1, b)) # 75.8 Âµs

import pandas as pd
s = pd.Series(a)
%timeit s.str[-1] # 965 Âµs
</code></pre>

<p>Even you have a DataFrame or Series object, you can convert it to a list first:</p>

<pre><code>%timeit s.tolist() #45.6 Âµs 
</code></pre>

python arrays pandas numpy