Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy: Convert and reshape 1D array to 2D array with zeros?

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   ]]
like image 239
Shantanu Avatar asked Sep 18 '25 06:09

Shantanu


1 Answers

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))
like image 161
Divakar Avatar answered Sep 19 '25 22:09

Divakar