What are the differences between numpy arrays and matrices? Which one should I use?

前端 未结 5 1928
野的像风
野的像风 2020-11-22 07:08

What are the advantages and disadvantages of each?

From what I\'ve seen, either one can work as a replacement for the other if need be, so should I bother using both

5条回答
  •  猫巷女王i
    2020-11-22 07:44

    Just to add one case to unutbu's list.

    One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.

    For example demean rows of a matrix or array:

    with matrix

    >>> m = np.mat([[1,2],[2,3]])
    >>> m
    matrix([[1, 2],
            [2, 3]])
    >>> mm = m.mean(1)
    >>> mm
    matrix([[ 1.5],
            [ 2.5]])
    >>> mm.shape
    (2, 1)
    >>> m - mm
    matrix([[-0.5,  0.5],
            [-0.5,  0.5]])
    

    with array

    >>> a = np.array([[1,2],[2,3]])
    >>> a
    array([[1, 2],
           [2, 3]])
    >>> am = a.mean(1)
    >>> am.shape
    (2,)
    >>> am
    array([ 1.5,  2.5])
    >>> a - am #wrong
    array([[-0.5, -0.5],
           [ 0.5,  0.5]])
    >>> a - am[:, np.newaxis]  #right
    array([[-0.5,  0.5],
           [-0.5,  0.5]])
    

    I also think that mixing arrays and matrices gives rise to many "happy" debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.

提交回复
热议问题