我有一个 numpy 数组,我将使用 np.ones((2,3)) 作为 MWE:
arr = [[1,1,1],
[1,1,1],
[1,1,1]]
我希望将行移动设定的整数。这将随着行的增加而增加。 将第一行移动 0 将第 5 行移动 4
我想所有行的行长度必须相等,给出以下列表: 给出这个:
arr = [[1,1,1,0,0],
[0,1,1,1,0],
[0,0,1,1,1]]
这是一个 MWE,实际数组取自 txt 文件,最大可达 (1000x96)。重要的值不仅仅是 1,而是 0->inf 之间的任何 float 。
有办法做到这一点吗?
(额外信息:这些数据用于二维热图绘制)
最佳答案
假设数组具有任意值,您可以使用:
# add enough "0" columns for the shift
arr2 = np.c_[arr, np.zeros((arr.shape[0], arr.shape[0]-1), dtype=arr.dtype)]
# get the indices as ogrid
r, c = np.ogrid[:arr2.shape[0], :arr2.shape[1]]
# roll the values
arr2 = arr2[r, c-r]
使用的输入:
arr = np.arange(1,10).reshape(3,3)
# array([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]])
输出:
array([[1, 2, 3, 0, 0],
[0, 4, 5, 6, 0],
[0, 0, 7, 8, 9]])
关于python - 将 numpy 数组每行移动一个递增的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71308321/