How can I convert and reshape the following list to the 2D array with zeros?
# original list
[1, 0.96, 0.92, 0.88]
# 2D Array
[[1 0 0 0 ]
[0.96 1 0 0 ]
[0.92 0.96 1 0 ]
[0.88 0.92 0.96 1 ]]
Here's a funky vectorized way. We can leverage np.lib.stride_tricks.as_strided
based scikit-image's view_as_windows
to get sliding windowed views and solve it.
from skimage.util.shape import view_as_windows
# a is input array (convert to array with np.array() is input is list)
p = np.r_[a[::-1], np.zeros(len(a)-1, dtype=a.dtype)]
out = view_as_windows(p,len(a))[::-1]
Alternatively, keep it native to NumPy -
m = len(a)
n = p.strides[0]
out = np.lib.stride_tricks.as_strided(p[m-1:], shape=(m,m), strides=(-n,n))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With