user40314 user40314 - 5 months ago 35
Python Question

Can one form a view into diagonal of ndarray in numpy

Simple slices form views into the parent array. The strides of the view is generically the multiple of the strides of the parent array.

Given 2d parent array with strides

(s0, s1)
, the 1D array with strides
gives the view in the diagonal of the parent array.

Is there a way to create such a view in top-level Python/numpy? Thank you in advance.


With as_strided I can do what you want:

In [298]: X=np.eye(5)
In [299]: X.strides
Out[299]: (40, 8)
In [300]: np.lib.stride_tricks.as_strided(X,shape=(5,),strides=(48,))
Out[300]: array([ 1.,  1.,  1.,  1.,  1.])

though some would argue the as_strided is a step closer to the 'guts' than most of numpy Python code.