[英]How to turn a numpy vector into a matrix, where each column in the matrix contains a range around the respective element in the initial vector?
Say I have a numpy vector array:假设我有一个 numpy 向量数组:
array([1, 2, 3])
and I want to convert this vector into a matrix where each column takes a range of +/- 2 around the respective element in the initial vector, such that my output matrix is:我想将此向量转换为一个矩阵,其中每列在初始向量中的各个元素周围取 +/- 2 的范围,这样我的 output 矩阵是:
array([[-1, 0, 1],
[ 0, 1, 2],
[ 1, 2, 3],
[ 2, 3, 4],
[ 3, 4, 5]])
what is the best (preferably vectorized) way to do this?最好的(最好是矢量化的)方法是什么?
You can do it with the following one-liner:您可以使用以下单线来做到这一点:
result = a + np.array([-1, 0, 1])[:, np.newaxis]
(I think, a more elegant solution). (我认为,一个更优雅的解决方案)。
The result is:结果是:
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
If the range depends on some parameter, say rng , you can do it as:如果范围取决于某个参数,比如rng ,你可以这样做:
rng = 2 # From x-2 to x+2
result = a + np.arange(-rng, rng + 1)[:, np.newaxis]
getting:得到:
array([[-1, 0, 1],
[ 0, 1, 2],
[ 1, 2, 3],
[ 2, 3, 4],
[ 3, 4, 5]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.