Python基础——np.where

Python

按条件查找数列中满足要求的值和索引,如:

#-------------------------------------------------------------------------

# 产生一个乱序的随机序列

>>> import numpy as np

>>> import random

>>> A = np.arange(10)

>>> A

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> random.shuffle(A)

>>> A

array([1, 7, 4, 9, 2, 3, 6, 0, 8, 5])

#---------------------------------------------------------------------------

>>> idx = [idx for (idx, val) in enumerata(A) if val > 5]

>>> idx

[1, 3, 6, 8]

>>> val = [val for (idx, val) in enumerata(A) if val > 5]

>>> val

[7, 9, 6, 8]

#----------------------------------------------------------------------------


np.where()

numpy中能够返回符合某一条件的下标函数:np.where(),只不过np.where()并不接受list类型的参数。

np.where()可用于接收3个参数,用于三目运算;也可用于接收1个参数,直接返回符合要求的下标

#-----------------------------------------------------------------------------

>>> import numpy as np

>>> A

array([1, 7, 4, 9, 2, 3, 6, 0, 8, 5])

>>> idx = np.where(A > 5)

(array([1, 3, 6, 8], dtype=int64),)

>>> A[idx]              #不建议如此操作

array([7, 9, 6, 8])

>>> A[A > 5]           #推荐操作

array([7, 9, 6, 8])

#----------------------------------------------------------------------------

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

—— np.where()[0] 表示行的索引;

—— np.where()[1] 则表示列的索引;


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

#---------------------------------------------------------------------------

#如果A%2==0成立,则执行A+1,否则执行A-1

>>> A

array([1, 7, 4, 9, 2, 3, 6, 0, 8, 5])

>>> B = np.where(A%2 == 0, A+1, A-1)   # 偶+1,奇-1

>>> B

array([0, 6, 5, 8, 3, 2, 7, 1, 9, 4])

#---------------------------------------------------------------------------

参考文献:http://blog.csdn.net/lanchunhui/article/details/49489205

参考文献:https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html



  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值