Python 如何对 numpy 数组进行条件数组算术?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3409255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:54:22  来源:igfitidea点击:

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

pythonnumpy

提问by pr0crastin8r

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

我试图更好地掌握 numpy 数组,所以我有一个示例问题要问他们:

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 的 numpy 数组。我想对 a 执行一个操作,该操作会增加其中所有小于 0 的值,并保留其余的值。例如,如果我有:

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!

谢谢!

采纳答案by unutbu

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

回答by John Kugelman

To mutate it:

要改变它:

a[a<0] += 1

To leave the original array alone:

不理会原始数组:

a+[a<0]

回答by Suhail Abdul Rehman Chougule

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.

只是为了添加到上面,在 numpy 数组中,我想根据 ascii 值减去一个值,以获得 0 到 35 之间的 ascii 0-9 和 AZ 值,并且不得不编写 for 循环,但上面的帖子向我展示了如何让它简短。所以我想把它贴在这里,感谢上面的帖子。

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