Multiplying across in a numpy array

前端 未结 6 981
借酒劲吻你
借酒劲吻你 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:08

    Normal multiplication like you showed:

    >>> import numpy as np
    >>> m = np.array([[1,2,3],[4,5,6],[7,8,9]])
    >>> c = np.array([0,1,2])
    >>> m * c
    array([[ 0,  2,  6],
           [ 0,  5, 12],
           [ 0,  8, 18]])
    

    If you add an axis, it will multiply the way you want:

    >>> m * c[:, np.newaxis]
    array([[ 0,  0,  0],
           [ 4,  5,  6],
           [14, 16, 18]])
    

    You could also transpose twice:

    >>> (m.T * c).T
    array([[ 0,  0,  0],
           [ 4,  5,  6],
           [14, 16, 18]])
    

提交回复
热议问题