python - NumPy:将一维数组转换并 reshape 为带有零的二维数组?

标签 python numpy numpy-ndarray

如何将以下列表转换并 reshape 为带零的二维数组?

# 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 获得滑动窗口 View 并解决它。

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

关于python - NumPy:将一维数组转换并 reshape 为带有零的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64533802/

相关文章:

Python 牛顿拉夫森小数根

python - 将 URL 包装为文件系统路径

python - Numpy 中的 3-D 矩阵乘法

python - 尝试人脸识别时出现明显的过时警告和值错误

python - 如何使用两个不同的用户运行 selenium webdriver?

python - 在文件中查找字符串

"\*"(文字星号字符)或 "\s"(空格)之间的 Python Regex 匹配选择

python - 如何避免在 numpy 中使用 for 循环?

python - Pandas 用特定列的列表替换 NaN 值

python - 如何根据另一个二维数组中给出的索引对二维数组进行切片