python 中 np.where

python或者numpy中能够返回符合某一条件的下标的函数是np.where(),不过np.where()并不接受list类型的参数,可见np.where()既可以接收三个参数,用于三目运算,也可接收一个参数,返回符合条件的下标。

>>a = np.array(a)
>>a
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
>>idx = np.where(a > 2)
>>idx
(array([2, 5, 8], dtype=int32),)
>>a[idx]               # 这种做法并不推荐
array([3, 3, 3])        
>>a[a>2]               # 推荐的做法
array([3, 3, 3])    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

注意,这种情况下,也即 np.where() 用于返回断言成立时的索引,返回值的形式为 arrays of tuple,由 np.array 构成的 tuple,一般 tuple 的 len 为2(当判断的对象是多维数组时),哪怕是一维数组返回的仍是 tuple,此时tuple 的 len 为 1;

  • np.where()[0] 表示行的索引,
  • np.where()[1] 则表示列的索引

np.where()用于三目运算的情况:

>>y = np.array([1, 2, 3, 4, 5, 6])  # 将奇数转换为偶数,偶数转换为奇数
>>y = np.where(y%2 == 0, y+1, y-1)
>>y 
array([0, 3, 2, 5, 4, 7])

np.where 函数是三元表达式 x if condition else y的矢量化版本

result = np.where(cond,xarr,yarr)

当符合条件时是x,不符合是y,常用于根据一个数组产生另一个新的数组。

栗子:假设有一个随机数生成的矩阵,希望将所有正值替换为2,负值替换为-2

arr = np.random.randn(4,4)
arr
np.where(arr>0,2,-2)

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pythonnp.where()函数用于返回满足条件的元素的下标。它可以接收一个参数,返回符合条件的下标,也可以接收三个参数,用于三目运算。\[1\]举个例子,如果我们有一个数组a = np.array(\[1, 2, 3, 1, 2, 3, 1, 2, 3\]),我们可以使用np.where(a > 2)来找到数组大于2的元素的下标,结果为(array(\[2, 5, 8\], dtype=int32),)。\[1\]另外,我们也可以使用a\[a > 2\]来直接返回满足条件的元素,结果为array(\[3, 3, 3\])。\[1\] 此外,np.where()函数还可以接收两个参数,用于替换数组的元素。\[3\]举个例子,如果我们有一个数组a = np.arange(12).reshape(\[3, 4\]),我们可以使用np.where(a > 5, 1, 0)来将数组大于5的元素替换为1,不大于5的元素替换为0,结果为array(\[\[0, 0, 0, 0\], \[0, 0, 1, 1\], \[1, 1, 1, 1\]\])。\[3\] #### 引用[.reference_title] - *1* [python np.where](https://blog.csdn.net/erinapple/article/details/80838359)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Python numpy使用记录3.数组元素筛选,np.where](https://blog.csdn.net/qq_41035283/article/details/124092350)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值