Why does the shape of a 1D array not show the number of rows as 1?

前端 未结 2 789
南笙
南笙 2020-12-29 20:55

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 colum

相关标签:
2条回答
  • 2020-12-29 21:32

    The concept of rows and columns applies 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.

    For a 2D version of the same array, consider the following instead:

    >>> a = numpy.array([[1,2,3,4]]) # notice the extra square braces
    >>> a.shape
    (1, 4)
    
    0 讨论(0)
  • 2020-12-29 21:41

    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:

    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:

    try:
        shape = (a.shape[0], a.shape[1])
    except IndexError:
        shape = (1, a.shape[0])
    
    print(shape)
    
    0 讨论(0)
提交回复
热议问题