Numpy 矩阵到数组
我正在使用numpy。我有一个 1 列 N 行的矩阵,我想从中获取一个包含 N 个元素的数组。
例如,如果我有 M = matrix([[1], [2], [3], [4]])
,我想得到 A = array([1, 2,3,4])
。
为了实现它,我使用 A = np.array(MT)[0]
。有谁知道一种更优雅的方法来获得相同的结果?
谢谢!
I am using numpy. I have a matrix with 1 column and N rows and I want to get an array from with N elements.
For example, if i have M = matrix([[1], [2], [3], [4]])
, I want to get A = array([1,2,3,4])
.
To achieve it, I use A = np.array(M.T)[0]
. Does anyone know a more elegant way to get the same result?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
如果你想要更具可读性的东西,你可以这样做:
同样,你也可以这样做:
A = np.asarray(M).reshape(-1)
,但这有点少易于阅读。If you'd like something a bit more readable, you can do this:
Equivalently, you could also do:
A = np.asarray(M).reshape(-1)
, but that's a bit less easy to read.https://numpy.org/doc/stable/reference/generate /numpy.matrix.A1.html
https://numpy.org/doc/stable/reference/generated/numpy.matrix.A1.html
您可以尝试以下变体:
You can try the following variant:
取决于你所说的优雅是什么意思,我想但这就是我会做的
depends what you mean by elegance i suppose but thats what i would do
如果您关心速度;但如果你关心记忆:
If you care for speed; But if you care for memory:
或者你可以尝试避免一些临时情况
Or you could try to avoid some temps with
首先,
Mv = numpy.asarray(MT)
,它为您提供一个 4x1 的二维数组。然后,执行
A = Mv[0,:]
,这会给你你想要的。您可以将它们放在一起,如 numpy.asarray(MT)[0,:]。First,
Mv = numpy.asarray(M.T)
, which gives you a 4x1 but 2D array.Then, perform
A = Mv[0,:]
, which gives you what you want. You could put them together, asnumpy.asarray(M.T)[0,:]
.这会将矩阵转换为数组
This will convert the matrix into array
ravel() 和 flatten() 来自 numpy 的函数我将在这里尝试两种技术。我想添加 Joe、Siraj,气泡和Kevad< /a>.
Ravel:
扁平化:
numpy.ravel()
更快,因为它是一个库级函数,不制作数组的任意副本。但是,如果您使用numpy.ravel()
,则数组 A 中的任何更改都会转移到原始数组 M 中。numpy.flatten()
比numpy.ravel()
慢。但是,如果您使用 numpy.flatten() 来创建 A,则 A 中的更改将不会转移到原始数组 M 中。numpy.squeeze()
和M.reshape(-1)
比numpy.flatten()
和numpy.ravel( )
。ravel() and flatten() functions from numpy are two techniques that I would try here. I will like to add to the posts made by Joe, Siraj, bubble and Kevad.
Ravel:
Flatten:
numpy.ravel()
is faster, since it is a library level function which does not make any copy of the array. However, any change in array A will carry itself over to the original array M if you are usingnumpy.ravel()
.numpy.flatten()
is slower thannumpy.ravel()
. But if you are usingnumpy.flatten()
to create A, then changes in A will not get carried over to the original array M.numpy.squeeze()
andM.reshape(-1)
are slower thannumpy.flatten()
andnumpy.ravel()
.来的有点晚了,希望对大家有帮助
Came in a little late, hope this helps someone,