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

Viewed 433

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   ]]
3 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))

The correct implementation with a for loop is:

import numpy as np

A = np.array([1, 0.96, 0.92, 0.88])
B = np.zeros((A.shape[0], A.shape[0]))

for i in range(A.shape[0]):
    B[i:, i] = A[:A.shape[0]-i]

There should be a way to vectorize this and to get rid of the for loop for efficiency.. Anyone has an idea?

I found this SO post which is relatively similar and has a bunch of vectorized implementations: Sliding window of M-by-N shape numpy.ndarray

Following works for you:

import numpy as np 

arr = np.array([1, 0.96, 0.92, 0.88])

arr_cp = np.zeros((arr.shape[0], arr.shape[0]))

for i in range(arr.shape[0]):
  arr_cp[i][:i+1] = np.flip(arr[:i+1])

print(arr_cp)

Output:

[[1.   0.   0.   0.  ]
 [0.96 1.   0.   0.  ]
 [0.92 0.96 1.   0.  ]
 [0.88 0.92 0.96 1.  ]]
Related