How do I do conditional array arithmetic on a numpy array?

前端 未结 3 1225
一向
一向 2020-12-06 10:35

I\'m trying to get a better grip on numpy arrays, so I have a sample question to ask about them:

Say I have a numpy array called a. I want to perform an operation on

相关标签:
3条回答
  • 2020-12-06 11:01

    Just to add to above,In numpy array I wanted to subtract a value based on the ascii value to get a value between 0 to 35 for ascii 0-9 and A-Z and had to write the for loops but the post above showed me how to make it short. So I thought of posting it here as thanks to the post above.

    The code below can be made short

    i = 0
    for y in y_train:
        if y < 58:
            y_train[i] = y_train[i]-48
        else :
            y_train[i] = y_train[i] - 55
        i += 1
    i = 0
    for y in y_test:
        if y < 58:
            y_test[i] = y_test[i]-48
        else :
            y_test[i] = y_test[i] - 55
        i += 1
    # The shortened code is below
    y_train[y_train < 58] -= 48
    y_train[y_train > 64] -= 55
    
    y_test[y_test < 58] -= 48
    y_test[y_test > 64] -= 55
    
    0 讨论(0)
  • 2020-12-06 11:17
    In [45]: a = np.array([1,2,3,-1,-2,-3])
    
    In [46]: a[a<0]+=1
    
    In [47]: a
    Out[47]: array([ 1,  2,  3,  0, -1, -2])
    
    0 讨论(0)
  • 2020-12-06 11:25

    To mutate it:

    a[a<0] += 1
    

    To leave the original array alone:

    a+[a<0]
    
    0 讨论(0)
提交回复
热议问题