当前位置: 首页 > 面试题库 >

为什么一维数组的形状未将行数显示为1?

贝财
2023-03-14
问题内容

我知道numpy数组有一个叫做shape的方法,该方法返回[行数,列数],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

但是,如果我的数组只有一行,那么它将返回[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

现在,如果该数组可能只有一行,如何获取numpy数组的行数?

谢谢


问题答案:


的概念适用于2D数组。但是,该数组numpy.array([1,2,3,4])是一维数组,因此只有一个维,因此shape正确地返回一个单值可迭代的数组。

对于同一阵列的2D版本,请考虑以下内容:

>>> a = numpy.array([[1,2,3,4]]) # notice the extra square braces
>>> a.shape
(1, 4)


 类似资料: