Multiplying across in a numpy array

前端 未结 6 982
借酒劲吻你
借酒劲吻你 2020-11-28 03:41

I\'m trying to multiply each of the terms in a 2D array by the corresponding terms in a 1D array. This is very easy if I want to multiply every column by the 1D array, as sh

6条回答
  •  误落风尘
    2020-11-28 04:22

    For those lost souls on google, using numpy.expand_dims then numpy.repeat will work, and will also work in higher dimensional cases (i.e. multiplying a shape (10, 12, 3) by a (10, 12)).

    >>> import numpy
    >>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
    >>> b = numpy.array([0,1,2])
    >>> b0 = numpy.expand_dims(b, axis = 0)
    >>> b0 = numpy.repeat(b0, a.shape[0], axis = 0)
    >>> b1 = numpy.expand_dims(b, axis = 1)
    >>> b1 = numpy.repeat(b1, a.shape[1], axis = 1)
    >>> a*b0
    array([[ 0,  2,  6],
       [ 0,  5, 12],
       [ 0,  8, 18]])
    >>> a*b1
    array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])
    

提交回复
热议问题