Python 为什么一维数组的形状没有将行数显示为 1?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39627852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does the shape of a 1D array not show the number of rows as 1?
提问by Yichuan Wang
I know that numpy array has a method called shape that returns [No.of rows, No.of columns], and shape[0] gives you the number of rows, shape[1] gives you the number of columns.
我知道 numpy 数组有一个名为 shape 的方法,它返回 [No.of rows, No.of columns],shape[0] 为您提供行数,shape[1] 为您提供列数。
a = numpy.array([[1,2,3,4], [2,3,4,5]])
a.shape
>> [2,4]
a.shape[0]
>> 2
a.shape[1]
>> 4
However, if my array only have one row, then it returns [No.of columns, ]. And shape[1] will be out of the index. For example
但是,如果我的数组只有一行,则它返回 [No.of columns, ]。并且 shape[1] 将超出索引。例如
a = numpy.array([1,2,3,4])
a.shape
>> [4,]
a.shape[0]
>> 4 //this is the number of column
a.shape[1]
>> Error out of index
Now how do I get the number of rows of an numpy array if the array may have only one row?
现在,如果数组可能只有一行,我如何获得 numpy 数组的行数?
Thank you
谢谢
回答by Moses Koledoye
The concept of rowsand columnsapplies when you have a 2D array. However, the array numpy.array([1,2,3,4])
is a 1D array and so has only one dimension, therefore shape
rightly returns a single valued iterable.
当您拥有二维数组时,行和列的概念适用。但是,该数组numpy.array([1,2,3,4])
是一维数组,因此只有一维,因此shape
正确返回单值可迭代对象。
For a 2D version of the same array, consider the following instead:
对于同一数组的 2D 版本,请考虑以下内容:
>>> a = numpy.array([[1,2,3,4]]) # notice the extra square braces
>>> a.shape
(1, 4)
回答by LinkBerest
Rather then converting this to a 2d array, which may not be an option every time - one could either check the len()
of the tuple returned by shape or just check for an index error as such:
而不是将其转换为二维数组,这可能不是每次都可以选择 - 可以检查len()
形状返回的元组的 ,或者只检查索引错误,如下所示:
import numpy
a = numpy.array([1,2,3,4])
print(a.shape)
# (4,)
print(a.shape[0])
try:
print(a.shape[1])
except IndexError:
print("only 1 column")
Or you could just try and assign this to a variable for later use (or return or what have you) if you know you will only have 1 or 2 dimension shapes:
或者,如果您知道只有 1 维或 2 维形状,您可以尝试将其分配给一个变量以供以后使用(或返回或您拥有的):
try:
shape = (a.shape[0], a.shape[1])
except IndexError:
shape = (1, a.shape[0])
print(shape)