一维numpy数组,该数组在新2D数组中的每个连续行向右移动 [英] 1D numpy array which is shifted to the right for each consecutive row in a new 2D array
问题描述
我正在尝试通过删除循环并仅在处理大型数据集时使用numpy数组来优化某些代码.
I am trying to optimise some code by removing for loops and using numpy arrays only as I am working with large data sets.
我想使用一维numpy数组,例如:
I would like to take a 1D numpy array, for example:
a = [1, 2, 3, 4, 5]
并生成一个二维numpy数组,其中每列中的值沿一个位置移动,例如,在上面的情况中,对于I,我希望有一个返回以下函数的函数:
and produce a 2D numpy array whereby the value in each column shifts along a place, for example in the case above for a I wish to have a function which returns:
[[1 2 3 4 5]
[0 1 2 3 4]
[0 0 1 2 3]
[0 0 0 1 2]
[0 0 0 0 1]]
我发现了一些使用strides函数执行类似于生产的示例,例如:
I have found examples which use the strides function to do something similar to produce, for example:
[[1 2 3]
[2 3 4]
[3 4 5]]
但是,我试图将我的每列向另一个方向移动.或者,可以将问题视为将a的第一个元素放在第一个对角线上,将第二个元素放在第二个对角线上,依此类推.但是,我想再次强调如何避免完全使用for,while或if循环.任何帮助将不胜感激.
However I am trying to shift each of my columns in the other direction. Alternatively, one can view the problem as putting the first element of a on the first diagonal, the second element on the second diagonal and so on. However, I would like to stress again how I would like to avoid using a for, while or if loop entirely. Any help would be greatly appreciated.
推荐答案
此类矩阵是 Toeplitz矩阵.您可以使用 scipy.linalg.toeplitz
来创建它:
Such a matrix is an example of a Toeplitz matrix. You could use scipy.linalg.toeplitz
to create it:
In [32]: from scipy.linalg import toeplitz
In [33]: a = range(1,6)
In [34]: toeplitz(a, np.zeros_like(a)).T
Out[34]:
array([[1, 2, 3, 4, 5],
[0, 1, 2, 3, 4],
[0, 0, 1, 2, 3],
[0, 0, 0, 1, 2],
[0, 0, 0, 0, 1]])
受@EelcoHoogendoorn的回答启发,这是一种变体,其使用的内存不及scipy.linalg.toeplitz
:
In [47]: from numpy.lib.stride_tricks import as_strided
In [48]: a
Out[48]: array([1, 2, 3, 4, 5])
In [49]: t = as_strided(np.r_[a[::-1], np.zeros_like(a)], shape=(a.size,a.size), strides=(a.itemsize, a.itemsize))[:,::-1]
In [50]: t
Out[50]:
array([[1, 2, 3, 4, 5],
[0, 1, 2, 3, 4],
[0, 0, 1, 2, 3],
[0, 0, 0, 1, 2],
[0, 0, 0, 0, 1]])
结果应被视为只读"数组.否则,当您更改元素时,您会感到有些惊讶.例如:
The result should be treated as a "read only" array. Otherwise, you'll be in for some surprises when you change an element. For example:
In [51]: t[0,2] = 99
In [52]: t
Out[52]:
array([[ 1, 2, 99, 4, 5],
[ 0, 1, 2, 99, 4],
[ 0, 0, 1, 2, 99],
[ 0, 0, 0, 1, 2],
[ 0, 0, 0, 0, 1]])
这篇关于一维numpy数组,该数组在新2D数组中的每个连续行向右移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!