Home > Software design >  Get the last non-null value per row of a 2D Numpy array
Get the last non-null value per row of a 2D Numpy array

Time:10-08

I have a 2D numpy array that looks like

a = np.array(
    [
        [1,2,np.nan,np.nan],
        [1,33,45,np.nan],
        [11,22,3,78],
    ]
)

I need to extract the last non null value per row i.e. [2, 45, 78]

Please guide on how to get it.

thanks

CodePudding user response:

Break this into two sub-problems.

  1. Remove nans from each row
  2. Select last element from the array
[r[~np.isnan(r)][-1] for r in a]

produces

[2.0, 45.0, 78.0]

CodePudding user response:

For a vectorial solution, you can try:

# get the index of last nan
idx = np.argmax(~np.isnan(a)[:, ::-1], axis=1)

# slice
a[np.arange(a.shape[0]), a.shape[1]-idx-1]

output: array([ 2., 45., 78.])

  • Related