2

I have got a three dimensional array with air pressure values in the form:

[[[1000 1010]
  [1005 990]]

[[950 960]
 [955 940]]

[[900 910]
[905 890]]]

The structure represents the pressure at different levels, so each element in the 2-d is ordered for each layer.

I would like to know at which level the pressure is 950 would be for each 2d element, getting a 2-d array with the index of the level for each element.

In a 1-D array like

a = [890, 940, 990]

I would use

a.searchsorted(950)

and the result would be 2, indicating that 950 would go at the 3rd position.

Is there a way to do it for all my array at once, without having to do it for each 2-d element?

5
  • I don't totally understand what you're after. If you take a single (m,n) array of pressure values corresponding to one level, are you saying that you want the rank of value v within the (m*n,) vector of sorted values for that level, e.g. np.sort(A[0,:,:].flat).searchsorted(v)? Then you just want to do the same thing for each level? Commented Jul 19, 2013 at 12:57
  • Well, I have multiple (m,n) arrays, one for each layer. I want to know between which levels a value would be, for each element in (m,n). i.e. For the element [1][1], the value 950 would be between the layer 0 and the layer 1. Commented Jul 19, 2013 at 13:23
  • I see, so it must be the case that for a given point A[:,i,j] the pressure values increase monotonically across levels (otherwise what you're asking for doesn't make sense) Commented Jul 19, 2013 at 13:26
  • Yes. Since they are atmospheric pressures, the values are accumulative for each point in the surface. Commented Jul 19, 2013 at 13:29
  • 1
    If you can use PyTorch, it supports N-D arrays: pytorch.org/docs/stable/generated/torch.searchsorted.html Commented Jul 20, 2022 at 18:28

1 Answer 1

6

You can apply the searchsorted function along an axis of your input array like this:

numpy.apply_along_axis(lambda a: a.searchsorted(950), axis = 1, arr = air_pr)

which should yield the intended result if I understand you correctly.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It gave me the solution, which is numpy.apply_along_axis(lambda a: a.searchsorted(950), axis = 0, arr = air_pressure) The array must be passed with arr =, and the axis is 0 (I still have to understand why). Also, the pressure values have to be ordered from lower to higher, but I think I will find a solution for that.
Ok. I had removed the 'arr =' to fit the command into one line, but of course Python will complain a non-keyword arg at that position.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.