How to multiply numpy 2D array with numpy 1D array?

后端 未结 2 1330
情话喂你
情话喂你 2020-12-28 14:50

The two arrays:

a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b

What I want is:

c = [[6,9,6],
     [25,         


        
相关标签:
2条回答
  • 2020-12-28 15:20

    Another strategy is to reshape the second array, so it has the same number of dimensions as the first array:

    c = a * b.reshape((b.size, 1))
    print(c)
    # [[ 6  9  6]
    #  [25 30  5]]
    

    Alternatively, the shape attribute of the second array can be modified in-place:

    b.shape = (b.size, 1)
    print(a.shape)  # (2, 3)
    print(b.shape)  # (2, 1)
    print(a * b)
    # [[ 6  9  6]
    #  [25 30  5]]
    
    0 讨论(0)
  • 2020-12-28 15:23

    You need to convert array b to a (2, 1) shape array, use None or numpy.newaxis in the index tuple:

    import numpy
    a = numpy.array([[2,3,2],[5,6,1]])
    b = numpy.array([3,5])
    c = a * b[:, None]
    

    Here is the document.

    0 讨论(0)
提交回复
热议问题