问题描述
我从MATLAB转到Python,在处理矩阵时遇到一些问题.
I came from MATLAB to Python and I face some problems dealing with matrices.
因此,我有一个矩阵(实现为np.array),我想操纵该矩阵的列.
So, I have a matrix (implemented as a np.array) and I want to manipulate columns of that matrix.
所以,我从初始化开始:
So, I begin with an initialization :
x = np.nan * np.ndarray((2,8))
y = np.nan * np.ndarray((2,8))
给出两个
array([[ nan, nan, nan, nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan, nan, nan, nan]])
现在,我想在y
内放置列向量v
以便以后在x
内进行计算
Now, I want to put a column vector v
inside y
to compute something inside x
later
v = np.array([[v1, v2]]) # if v = np.array([[v1], [v2]], doesn't compute on next line
y[:,0] = np.copy(v)
x[:,0] = y[:,0] + someRandomVector
它向我返回一个错误:
ValueError: could not broadcast input array from shape (2,2) into shape (2)
我认为问题出在以下事实:x[:,0]
没有给出我期望的列向量,而是
I think the problem comes from the fact that x[:,0]
does not give a column vector as I expected but rather
>>> x[:,0]
array([ nan, nan])
有什么想法或提示可能会有所帮助吗?
Any idea or tips that might help?
推荐答案
>>>x[:,0:1]
print x.[:,0:1].shape
(2,1)
在此帖子解释了动机以及如何在numpy中管理数组.
In this post is explained the motivation and how the array is managed in numpy.
如果您想提取具有更多内容的第五列 超过5列,则可以使用X [:,4:5].如果您想查看 第3-4行和第5-7列,则可以执行X [3:5,5:8].希望你能 这个想法.
If you wanted to extract the fifth column of something that had more than 5 total columns, you could use X[:,4:5]. If you wanted a view of rows 3-4 and columns 5-7, you would do X[3:5,5:8]. Hopefully you get the idea.
这篇关于numpy:要提取一列,给出一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!