numpy subtract/add 1d array from 2d array

后端 未结 2 635
北海茫月
北海茫月 2020-12-06 04:57

I have the following 2D-array:

a = array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 7,  8,  9],
           [10, 11, 12],
           [13, 14, 15]])
         


        
2条回答
  •  遥遥无期
    2020-12-06 05:27

    You need to convert array b to a (2, 1) shape array, use None or numpy.newaxis in the index tuple. Here is the Indexing of Numpy array.

    You can do it Like:

    import numpy
    
    a = numpy.array([[ 1,  2,  3],
               [ 4,  5,  6],
               [ 7,  8,  9],
               [10, 11, 12],
               [13, 14, 15]])
    
    b = numpy.array([ 1,  2,  3,  4,  5])
    c=a - b[:,None]
    print c
    

    Output:

    Out[2]: 
    array([[ 0,  1,  2],
           [ 2,  3,  4],
           [ 4,  5,  6],
           [ 6,  7,  8],
           [ 8,  9, 10]])
    

提交回复
热议问题