1

I have a 2D array which describes index ranges for a 1D array like

z = np.array([[0,4],[4,9]])

The 1D array

a = np.array([1,1,1,1,0,0,0,0,0,1,1,1,1])

I want to have a view on the 1D array with the index range defined by z. So, for only the first range

 a[z[0][0]:z[0][1]]

How to get it for all ranges? Is it possible to use as_strided with unequal lengths defined by z as shape? I want to avoid to copy data, actually I only want a different view on a for further computation.

2
  • 1
    Because of the irregular window lengths, don't think this would be possible. Commented Nov 29, 2017 at 8:34
  • So, what's wrong with a[z[0][0]:z[0][1]], a[z[1][0]:z[1][1]] and so on? Commented Nov 29, 2017 at 8:51

2 Answers 2

1
In [66]: a = np.array([1,1,1,1,0,0,0,0,0,1,1,1,1])
In [67]: z = np.array([[0,4],[4,9]])

So generating the slices from the rows of z we get 2 arrays:

In [68]: [a[x[0]:x[1]] for x in z]
Out[68]: [array([1, 1, 1, 1]), array([0, 0, 0, 0, 0])]

Individually those arrays are views. But together they aren't an array. The lengths diff, so they can't be vstacked into a (2,?) array. They can be hstacked but that won't be a view.

The calculation core of np.array_split is:

sub_arys = []
sary = _nx.swapaxes(ary, axis, 0)
for i in range(Nsections):
    st = div_points[i]
    end = div_points[i + 1]
    sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0))

Ignoring the swapaxes bit, this is doing the same thing as my list comprehension.

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

2 Comments

Then I could also use split directly with the change points as splitting points, in this case np.split(a, [4,9]). The question is what is faster? I think split copies the data, so the for loop with the ranges is faster?
np.split returns sub-arrays (view, in this context). If b = np.split(a, [4, 9]) and a[1] = -1, then b[0][1] == -1
1
for x, y in z:
    array_view = a[x:y]
    # do something with array_view

Comments

Your Answer

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