numpy:要提取一列,给出一行 [英] numpy : Want to extract a column, gives a row

查看:575
本文介绍了numpy:要提取一列,给出一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从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.

这对您的情况意味着,当您编写X [:,4]时,您将具有一个片表示法和一个常规索引表示法.切片符号表示沿第一个维度的所有索引(由于数组有两行,因此分别为0和1),而4表示沿第二个维度的第五个元素.正则索引的每个实例基本上都会将返回的对象的维数减一,因此,由于X是2D数组,并且有一个正则索引,您将获得一维结果. Numpy只是将一维数组显示为行向量.如果想获得与开始时相同的尺寸,那么诀窍就是使用所有切片索引,就像我在本文顶部示例中所做的那样.

What this means for your case is that when you write X[:,4], you have one slice notation and one regular index notation. The slice notation represents all indices along the first dimension (just 0 and 1, since the array has two rows), and the 4 represents the fifth element along the second dimension. Each instance of a regular index basically reduces the dimensionality of the returned object by one, so since X is a 2D array, and there is one regular index, you get a 1D result. Numpy just displays 1D arrays as row vectors. The trick, if you want to get out something of the same dimensions you started with, is then to use all slice indices, as I did in the example at the top of this post.

如果您想提取具有更多内容的第五列 超过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:要提取一列,给出一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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