将NumPy矩阵复制到NumPy数组中 [英] Copy NumPy matrix into NumPy array

查看:85
本文介绍了将NumPy矩阵复制到NumPy数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用cvxpy来解决优化问题.我想将输出matrix存储到ndarray中.

I am using cvxpy to solve an optimization problem. I want to store the output, a matrix into a ndarray.

这是简化的测试用例. a表示从cvxpy返回的值.

This is the reduced test case. a representing the returned value from cvxpy.

import numpy as np

z = np.zeros((3,7))
a = np.matrix("[1; 2; 3]")
z[0, 0] = a[0]
z[1, 0] = a[1]
z[2, 0] = a[2]

我想用更好的内容替换最后三行,但是我尝试的所有操作都会导致错误.例如,

I would like to replace the last three lines with something better, but everything I try results in an error. E.g.,

>>> z[:, 0] = a
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: could not broadcast input array from shape (3,1) into shape (3)
>>> np.copyto(z[:, 0], a)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: could not broadcast input array from shape (3,1) into shape (3)

我会有所帮助.谢谢.

推荐答案

一种简单的方法是使用列索引列表为z建立索引,然后在其中简单地分配NumPy矩阵a-

One simple way would be to use a list of the column index for indexing into z and then simply assign the NumPy matrix a there -

z[:,[0]] = a

另一种方法是使用矩阵a的转置,该矩阵将是要分配给z-

Another way would be to use the transpose of the matrix a, which would be a row vector to assign into the sliced version of the first column in z -

z[:,0] = a.T

这篇关于将NumPy矩阵复制到NumPy数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆