[英]python matrix operation with numpy
I have a python array such as:我有一个 python 数组,例如:
[[1],
[2],
[3],
[4]
]
I want to make it to:
[ [1 0 0 0],
[2 0 0 0 ],
[3 0 0 0],
[4 0 0 0]
]
What is the python way to do this?这样做的python方法是什么? Suppose I use numpy.
假设我使用 numpy.
numpy.pad(array, pad_width, mode=None, **kwargs)
: numpy.pad(array, pad_width, mode=None, **kwargs)
:
>>> np.pad(a, pad_width=((0, 0), (0, 3)), mode='constant', constant_values=0)
array([[1, 0, 0, 0],
[2, 0, 0, 0],
[3, 0, 0, 0],
[4, 0, 0, 0]])
Create a row vector using numpy.eye .使用numpy.eye创建一个行向量。
>>> import numpy as np
>>> a = np.array([[1],[2],[3],[4]])
>>> b = np.eye(1, 4)
>>> b
array([[ 1., 0., 0., 0.]]
>>> c = a * b
>>> c
array([[ 1., 0., 0., 0.],
[ 2., 0., 0., 0.],
[ 3., 0., 0., 0.],
[ 4., 0., 0., 0.]])
Concatenation of zeros might be faster since this example uses matrix multiplication to achieve the required result and not allocation of the required size.零的串联可能会更快,因为此示例使用矩阵乘法来实现所需的结果,而不是分配所需的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.