2016-09-21 458 views
14

我知道numpy数组有一个称为shape的方法,它返回[行号,列数],形状[0]为您提供行数,形状[1]给出你的列数。numpy数组中的行数

a = numpy.array([[1,2,3,4], [2,3,4,5]]) 
a.shape 
>> [2,4] 
a.shape[0] 
>> 2 
a.shape[1] 
>> 4 

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

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

谢谢

回答

25

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

对于相同阵列的2D版本,考虑代替以下:

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

拯救我的生命!非常感谢 –

+0

@YichuanWang如果你从一个一维数组开始('a_1d = numpy.array([1,2,3,4])'),你总是可以把它转换成一个二维数组例如'a_2d = a_1d [无,:]' – donkopotamus

2

相反然后转换此为2D阵列,这可能不是一个选项每当 - 一个既可以检查的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") 

或者你可以尝试,并指定这个以供将来使用一个变量(或退货或者你有什么)如果你知道你将只有1或2维的形状:

try: 
    shape = (a.shape[0], a.shape[1]) 
except IndexError: 
    shape = (1, a.shape[0]) 

print(shape) 
+0

谢谢。由于我是python的新手,我甚至没有想过使用这种“尝试除外”的方式。你的回答让人大开眼界! –