Numpy array dimensions

前端 未结 8 526
谎友^
谎友^ 2020-11-30 17:13

I\'m currently trying to learn Numpy and Python. Given the following array:

import numpy as np
a = np.array([[1,2],[1,2]])

Is there a funct

相关标签:
8条回答
  • 2020-11-30 17:29

    It is .shape:

    ndarray.shape
    Tuple of array dimensions.

    Thus:

    >>> a.shape
    (2, 2)
    
    0 讨论(0)
  • 2020-11-30 17:30

    a.shape is just a limited version of np.info(). Check this out:

    import numpy as np
    a = np.array([[1,2],[1,2]])
    np.info(a)
    

    Out

    class:  ndarray
    shape:  (2, 2)
    strides:  (8, 4)
    itemsize:  4
    aligned:  True
    contiguous:  True
    fortran:  False
    data pointer: 0x27509cf0560
    byteorder:  little
    byteswap:  False
    type: int32
    
    0 讨论(0)
  • 2020-11-30 17:34
    rows = a.shape[0] # 2 
    cols = a.shape[1] # 2
    a.shape #(2,2)
    a.size # rows * cols = 4
    
    0 讨论(0)
  • 2020-11-30 17:36

    You can use .ndim for dimension and .shape to know the exact dimension

    var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]])
    
    var.ndim
    # displays 2
    
    var.shape
    # display 6, 2
    

    You can change the dimension using .reshape function

    var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]]).reshape(3,4)
    
    var.ndim
    #display 2
    
    var.shape
    #display 3, 4
    
    0 讨论(0)
  • 2020-11-30 17:40
    import numpy as np   
    >>> np.shape(a)
    (2,2)
    

    Also works if the input is not a numpy array but a list of lists

    >>> a = [[1,2],[1,2]]
    >>> np.shape(a)
    (2,2)
    

    Or a tuple of tuples

    >>> a = ((1,2),(1,2))
    >>> np.shape(a)
    (2,2)
    
    0 讨论(0)
  • 2020-11-30 17:49

    You can use .shape

    In: a = np.array([[1,2,3],[4,5,6]])
    In: a.shape
    Out: (2, 3)
    In: a.shape[0] # x axis
    Out: 2
    In: a.shape[1] # y axis
    Out: 3
    
    0 讨论(0)
提交回复
热议问题