multiply numpy ndarray with 1d array along a given axis

前端 未结 5 1898
死守一世寂寞
死守一世寂寞 2021-01-04 06:40

It seems I am getting lost in something potentially silly. I have an n-dimensional numpy array, and I want to multiply it with a vector (1d array) along some dimension (whi

5条回答
  •  难免孤独
    2021-01-04 07:10

    You could build a slice object, and select the desired dimension in that:

    import numpy as np
    
    a = np.arange(18).reshape((3,2,3))
    b = np.array([1,3])
    
    ss = [None for i in range(a.ndim)]
    ss[1] = slice(None)    # set the dimension along which to broadcast
    
    print ss  #  [None, slice(None, None, None), None]
    
    c = a*b[ss]
    

提交回复
热议问题