python - 将 numpy 数组每行移动一个递增的值

标签 python arrays numpy

我有一个 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/

相关文章:

python - 如何增加 flask 形式的 bool 字段的大小?

python - Numpy:智能矩阵乘法到稀疏结果矩阵

python - NumPy:新旧数据描述符的大小不匹配

python-3.x - 我想从 Python 中的点云生成网格

python - 无法弄清楚导致 IOError 的原因是什么

python - 使用 Python 从 HTML 中提取歌曲长度和大小

Python 请求填写表单

c# - 与带分隔符的 String.Split 相反 (.net)

python - 用数组重写代码

c - 如何使用函数和输出 C