I have a 3D array in numpy that includes nans. I need to return the value with the greatest index position along the 0 axis. The answer would reduce to a 2D array.
There are a lot of questions about finding the index position of a maximum value along an axis (How to get the index of a maximum element in a numpy array along one axis), but that is different than what I need.
Example 3D array:
>>> import numpy as np
>>> foo = np.asarray([[[7,4,6],[4,2,11], [7,8,9], [4,8,2]],[[1,2,3],[np.nan,5,8], [np.nan,np.nan,10], [np.nan,np.nan,7]]])
>>> foo
array([[[ 7., 4., 6.],
[ 4., 2., 11.],
[ 7., 8., 9.],
[ 4., 8., 2.]],
[[ 1., 2., 3.],
[ nan, 5., 8.],
[ nan, nan, 10.],
[ nan, nan, 7.]]])
I thought I was getting close using np.where but it returns all elements that are not nan. Not quite what I need because I want a (4,3)
array.
>>> zoo = foo[np.where(~np.isnan(foo))]
>>> zoo
array([ 7., 4., 6., 4., 2., 11., 7., 8., 9., 4., 8.,
2., 1., 2., 3., 5., 8., 10., 7.])
The answer I need is:
>>> ans = np.asarray([[1,2,3], [4,5,8], [7,8,10], [4,8,7]])
>>> ans
array([[ 1, 2, 3],
[ 4, 5, 8],
[ 7, 8, 10],
[ 4, 8, 7]])
EDIT: I edited the foo example array to make the question more clear.