[英]Transform an array of shape (n,) to a numpy array of shape (n,1)
I have an array that I read from a .npz
file with numpy, that has a shape I can not really explain. 我有一个数组,我从.npz
文件读取numpy,有一个我无法解释的形状。
When I print the array I get numbers in the following form: 当我打印数组时,我得到以下形式的数字:
[1 2 3 2 1 8 9 8 3 4 ...]
without any comma separating them 没有任何逗号分隔它们
I would like to transform this array into a numpy array of dimensions (n,1)
where n is the number of elements and 1 is the number of columns. 我想将此数组转换为numpy维数组(n,1)
,其中n是元素数,1是列数。
Is there an elegant way of doing it? 有一种优雅的方式吗?
The shape (n, )
means its a one-dimensional array of n
length . 形状(n, )
表示其长度为n
的一维数组。 If you think the shape (n, 1)
represents a one-dimensional array, then it does not, (n,1)
represents a two dimensional array of n sub-arrays, with each sub-array having 1 element. 如果你认为形状(n, 1)
代表一维数组,那么它不会, (n,1)
代表n个子数组的二维数组,每个子数组有1个元素。
If what you really want is an array of shape (n, 1)
, you can use ndarray.reshape()
with shape (-1, 1)
- 如果你真正想要的是一个形状数组(n, 1)
,你可以使用形状为(-1, 1)
ndarray.reshape()
(-1, 1)
-
array.reshape((-1,1))
Demo - 演示 -
In [64]: na
Out[64]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [65]: str(na)
Out[65]: '[0 1 2 3 4 5 6 7 8 9]'
In [66]: na.reshape((-1,1))
Out[66]:
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
In [67]: na.reshape((-1,1)).shape
Out[67]: (10, 1)
As you can see this moves the array from being a 1d array to a 2d array with each inner row (inner array) containing only 1 element. 如您所见,这将数组从1d数组移动到2d数组,每个内部行(内部数组)只包含1个元素。 This may not be what you want. 这可能不是你想要的。 The output like - 输出像 -
[1 2 3 2 1 8 9 8 3 4 ...]
is just the str()
result of a numpy array, it does mean the elements internally are not separated. 只是numpy数组的str()
结果,它确实意味着内部的元素不是分开的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.