Yic*_*ang 30 python arrays numpy
我知道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
Run Code Online (Sandbox Code Playgroud)
但是,如果我的数组只有一行,则返回[Numberof columns,].并且形状[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
Run Code Online (Sandbox Code Playgroud)
现在如果数组可能只有一行,如何获取numpy数组的行数?
谢谢
Mos*_*oye 38
当您拥有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)
Run Code Online (Sandbox Code Playgroud)