如何更改numpy数组中的值 [英] How to change values in numpy array

查看:864
本文介绍了如何更改numpy数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import numpy as np
a=np.array([[4,2,6],[3,6,5]])
b=np.array([3,5])

我想将大于"b"中数字的"a"中的数字更新为np.nan.如果它们小于或等于我不希望更改它.我想将"a"的第一行与"b"的第一标量进行比较,将"a"的第二行与"b"的第二标量进行比较.

I want to update the numbers in "a" which are bigger than the numbers in "b" to np.nan. If they are smaller or equal i don't want it to be changed. I want to compare the first row of "a" to the first scalar of "b" and the second row of "a" to the second scalar of "b".

例如

a = array([[4, 2, 6],
           [3, 6, 5]])

更新后的值应为:

array([[nan, 2, nan],
       [3, nan, 5]])

我已经尝试过了:

for i in range(2):
     a[i]=np.where(a[i]<=b[i],a[i],np.nan)

但是它不起作用.请帮助我!

But it doesn't work. HELP ME PLEASE!!

推荐答案

您可以这样写:

import numpy as np
a=np.array([[4,2,6],[3,6,5]])
b=np.array([3,5])

# shape in compared axis must be the same or one of their length must be equal 1
# in this case their shape is b(2,1) and a(2,3)

a = np.where(a <= b.reshape(b.shape[0],1), a, np.nan)
print(a)

但是在更困难的情况下,我不确定它是否可以工作

but in more difficult cases I'm not sure, that it will work

这篇关于如何更改numpy数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆