形状为(N,1)的数组与形状为(N)的数组有什么区别?以及如何在两者之间转换? [英] What is the difference between an array with shape (N,1) and one with shape (N)? And how to convert between the two?
问题描述
这里的Python新手来自MATLAB背景.
Python newbie here coming from a MATLAB background.
我有一个1列数组,我想将该列移到3列数组的第一列中.在MATLAB的背景下,这就是我要做的:
I have a 1 column array and I want to move that column into the first column of a 3 column array. With a MATLAB background this is what I would do:
import numpy as np
A = np.zeros([150,3]) #three column array
B = np.ones([150,1]) #one column array which needs to replace the first column of A
#MATLAB-style solution:
A[:,0] = B
但是,这不起作用,因为A的形状"为(150,3),而B的形状"为(150,1).显然,命令A [:,0]的形状"为(150).
However this does not work because the "shape" of A is (150,3) and the "shape" of B is (150,1). And apparently the command A[:,0] results in a "shape" of (150).
现在(150,1)和(150)有什么区别?它们不是同一件事:列向量吗?为什么Python不够聪明"以致于我想将列向量B放入A的第一列?
Now, what is the difference between (150,1) and (150)? Aren't they the same thing: a column vector? And why isn't Python "smart enough" to figure out that I want to put the column vector, B, into the first column of A?
是否有一种简单的方法可以将形状为(N,1)的1列向量转换为形状(N)的1列向量?
我是Python的新手,这看起来很愚蠢,因为MATLAB可以做得更好...
I am new to Python and this seems like a really silly thing that MATLAB does much better...
推荐答案
Use squeeze method to eliminate the dimensions of size 1.
A[:,0] = B.squeeze()
或者只是以一维创建B:
Or just create B one-dimensional to begin with:
B = np.ones([150])
NumPy保持一维数组和二维数组之间的区别,其中维数之一为1的事实是合理的,尤其是当人们开始使用n维数组时.
The fact that NumPy maintains a distinction between a 1D array and 2D array with one of dimensions being 1 is reasonable, especially when one begins working with n-dimensional arrays.
要回答标题中的问题:形状为(3,)
的数组(例如
To answer the question in the title: there is an evident structural difference between an array of shape (3,)
such as
[1, 2, 3]
和形状为(3, 1)
的数组,例如
[[1], [2], [3]]
这篇关于形状为(N,1)的数组与形状为(N)的数组有什么区别?以及如何在两者之间转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!