Home > Software design >  Find the line index of the first line in a 2D array thjat is non full of NaN
Find the line index of the first line in a 2D array thjat is non full of NaN

Time:08-13

I have 2D array with plenty of lines fully fed with NaN values. I would like to find where the first real number is present, i.e. the line number where it appears. My simplified array looks like this:

m = np.array([[np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, 17, np.nan],[np.nan, 18, 25]])

The expected result is 2, the line number where 17 appears! Thank you

CodePudding user response:

You can grab the first row where at least one element is not nan using sum and isnan:

np.argmax((~np.isnan(m)).sum(axis=1) > 0)

Edit

Based on I'mahdi's answer, I realize you can also just use any:

np.argmax((~np.isnan(m)).any(axis=1))

CodePudding user response:

You can use numpy.isnan() and numpy.argmax().

m = np.array([[np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, 17, np.nan],[np.nan, 18, 25]])
r = np.argmax((~np.isnan(m)).any(1))
print(r)
# 2

If you want to find any indexes you can use numpy.argwhere() in this example if you want to find first and second:

np.argwhere((~np.isnan(m)).any(1))
# [[2] first is exist in index 2
#  [3] second is exist in index 3
# ]
  • Related