Conditional operations on numpy arrays

后端 未结 3 1707
深忆病人
深忆病人 2021-01-04 21:48

I\'m new to NumPy, and I\'ve encountered a problem with running some conditional statements on numpy arrays. Let\'s say I have 3 numpy arrays that look like this:

a:

相关标签:
3条回答
  • 2021-01-04 22:05

    You can use numpy.where:

    np.where((a > 3) & (b > 8), c + b*2, c)
    #array([[ 0, 18,  0,  0],
    #       [ 0,  0,  0,  0],
    #       [ 0,  0,  0,  0]])
    

    Or arithmetically:

    c + b*2 * ((a > 3) & (b > 8))
    #array([[ 0, 18,  0,  0],
    #       [ 0,  0,  0,  0],
    #       [ 0,  0,  0,  0]])
    
    0 讨论(0)
  • 2021-01-04 22:21

    The problem is that you mask the receiving part, but do not mask the sender part. As a result:

    c[(a > 3) & (b > 8)]+=b*2
    # ^ 1x1 matrix        ^3x4 matrix
    

    The dimensions are not the same. Given you want to perform element-wise addition (based on your example), you can simply add the slicing to the right part as well:

    c[(a > 3) & (b > 8)]+=b[(a > 3) & (b > 8)]*2

    or make it more efficient:

    mask = (a > 3) & (b > 8)
    c[mask] += b[mask]*2
    0 讨论(0)
  • 2021-01-04 22:21

    A slight change in the numpy expression would get the desired results:

    c += ((a > 3) & (b > 8)) * b*2
    

    Here First I create a mask matrix with boolean values, from ((a > 3) & (b > 8)), then multiply the matrix with b*2 which in turn generates a 3x4 matrix which can be easily added to c

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