[英]NumPy: Convert and reshape 1D array to 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 ]]
這是一種時髦的矢量化方式。 我們可以利用基於np.lib.stride_tricks.as_strided
的scikit-image's view_as_windows
來獲取滑動窗口視圖並解決它。
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]
或者,將其保留為 NumPy -
m = len(a)
n = p.strides[0]
out = np.lib.stride_tricks.as_strided(p[m-1:], shape=(m,m), strides=(-n,n))
使用for
循環的正確實現是:
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]
應該有一種方法可以對此進行矢量化並擺脫 for 循環以提高效率。任何人都有想法嗎?
我發現這個 SO 帖子比較相似並且有一堆矢量化實現: 滑動 window of M-by-N shape numpy.ndarray
以下為您工作:
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. ]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.