开发者

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

I'm trying to get a better grip开发者_C百科 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 a that increments all the values inside it that are less than 0 and leaves the rest alone. for example, if I had:

a = np.array([1,2,3,-1,-2,-3])

I would want to return:

([1,2,3,0,-1,-2])

What is the most compact syntax for this?

Thanks!


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])


To mutate it:

a[a<0] += 1

To leave the original array alone:

a+[a<0]


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜