python - 将一维 numpy 数组转换为矩阵的顶部三角形

标签 python numpy

是否可以采用包含 171 个值的一维 numpy 数组并将这些值放入 18X18 矩阵的顶部三角形中?

我觉得我应该能够使用 np.triu_indices 以某种方式做到这一点,但我不太明白!

谢谢!

最佳答案

参见 What is the most efficient way to get this kind of matrix from a 1D numpy array?Copy flat list of upper triangle entries to full matrix?

大致的做法是

result = np.zeros(...)
ind = np.triu_indices(...)
result[ind] = values

详细信息取决于目标数组的大小,以及您的值在目标中的布局。

In [680]: ind = np.triu_indices(4)
In [681]: values = np.arange(16).reshape(4,4)[ind]
In [682]: result = np.zeros((4,4),int)
In [683]: result[ind]=values
In [684]: values
Out[684]: array([ 0,  1,  2,  3,  5,  6,  7, 10, 11, 15])
In [685]: result
Out[685]: 
array([[ 0,  1,  2,  3],
       [ 0,  5,  6,  7],
       [ 0,  0, 10, 11],
       [ 0,  0,  0, 15]])

关于python - 将一维 numpy 数组转换为矩阵的顶部三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34913483/

相关文章:

python - 寻找 numpy 模式向量

python - 在运算符中, float ("NaN")和 np.nan

arrays - 使用 Pandas 数据框进行数据操作

Python 库 "PDFrw"写入的注释在单击字段之前保持不可见

python - 枚举 libreoffice 文档中的 FieldMark

python - 绘制 Pandas DataFrame 的累积返回

python - 当 x 值为日期时间时,如何使用 polyfit 获得最佳拟合曲线?

python - scipy.interpolate.griddata 和 scipy.interpolate.Rbf 之间的区别

python - 当 python 对象被销毁时如何做某事?

python - 使用 scipys generic_filter 实现 "Kurtosis filter"