3

Say I have an array that looks like the following:

arr = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]

And I have another array slicer = [1,3,2]. I want to apply these values as the slice index over axis 0 measure along axis 1.

This doesn't work (and in fact contains no way of specifying that the along part is axis 1 in an ndarray) but suppose I tried arr[:slicer, :]

I would hope to obtain,

out = [[1,   2,   3],
       [nan, 5,   6],
       [nan, 8, nan]]

which is the combination of applying the slice arr[:1, :], arr[:3, :], arr[:2, :] and then selecting from those the 1st, 2nd and 3rd columns respectively and reassembling into the array above, dropping missing values.

I want to avoid loops and trying to find a fast vectorised solution

0

1 Answer 1

7

For this operation you need to first generate a boolean index mask that marks all fields you want to set to nan. Broadcasting makes it easy to perform an "outer comparison" that yields the desired result

slicer = numpy.asarray([1, 3, 2])
mask = numpy.arange(3)[:, None] >= slicer
mask
# array([[False, False, False],
#        [ True, False, False],
#        [ True, False,  True]])

You can then simply use this mask to index data

data = numpy.arange(1, 10, dtype=float).reshape(3, 3)
data[mask] = numpy.nan
data
# array([[ 1.,  2.,  3.],
#        [nan,  5.,  6.],
#        [nan,  8., nan]])
Sign up to request clarification or add additional context in comments.

1 Comment

marvellous result, in record time. Thanks.

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.