How to copy lower triangle to upper triangle for a 4 dimension array in Numpy Python?

爱⌒轻易说出口 提交于 2020-12-14 23:50:33

问题


The objective is to copy the lower triangle to upper triangle. Based on the suggestion produced in the OP, the following code was drafted.

import numpy as np

lw_up_pair = np.tril_indices(4, -1)
arr=np.zeros((4,4,1,1))

arr[1,:1,:,0]=1
arr[2,:2,0,0]=2
arr[3,:3,0,0]=3
arr = arr + arr.T - np.diag(np.diag(arr))

However, it given an error

ValueError: Input must be 1- or 2-d.

May I know how handle this issue?

The expected output is as below

[[[0.]],, [[1.]],, [[2.]],, [[3.]]]
[[[1.]],, [[0.]],, [[2.]],, [[3.]]]
[[[2.]],, [[2.]],, [[0.]],, [[3.]]]
[[[3.]],, [[3.]],, [[3.]],, [[0.]]]

回答1:


Before performing your triangle-copy, apply a "squeeze" to squeeze out the last two axes (which have length of 1 each).

This leaves you with a 2-D array.

Then, after performing your triangle-copy, re-introduce the axes that you had squeezed out:

arr = np.squeeze(arr)
arr = arr + arr.T - np.diag(np.diag(arr))
arr = arr[...,None, None]


来源:https://stackoverflow.com/questions/65051653/how-to-copy-lower-triangle-to-upper-triangle-for-a-4-dimension-array-in-numpy-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!