zoukankan      html  css  js  c++  java
  • 数据科学:numpy.where() 的用法

    numpy.where() 有两种用法:

    1. np.where(condition, x, y)

    • 满足条件(condition),输出x,不满足输出y
    • 情景(一)

    • >>> aa = np.arange(10)
      >>> np.where(aa,1,-1)
      array([-1,  1,  1,  1,  1,  1,  1,  1,  1,  1])  # 0为False,所以第一个输出-1
      >>> np.where(aa > 5,1,-1)
      array([-1, -1, -1, -1, -1, -1,  1,  1,  1,  1])
      
      >>> np.where([[True,False], [True,True]],    # 官网上的例子
                   [[1,2], [3,4]],
                   [[9,8], [7,6]])
      array([[1, 8],
             [3, 4]])
    • 情景(二)

    • >>> a = 10
      >>> np.where([[a > 5,a < 5], [a == 10,a == 7]],
                   [["chosen","not chosen"], ["chosen","not chosen"]],
                   [["not chosen","chosen"], ["not chosen","chosen"]])
      
      array([['chosen', 'chosen'],
             ['chosen', 'chosen']], dtype='<U10')

    2. np.where(condition)

    只有条件 (condition),没有x和y,则输出满足条件 (即非0) 元素的坐标 (等价于numpy.nonzero)。这里的坐标以tuple的形式给出,通常原数组有多少维,输出的tuple中就包含几个数组,分别对应符合条件元素的各维坐标。

    • >>> a = np.array([2,4,6,8,10])
      >>> np.where(a > 5)             # 返回索引
      (array([2, 3, 4]),)   
      >>> a[np.where(a > 5)]              # 等价于 a[a>5]
      array([ 6,  8, 10])
      
      >>> np.where([[0, 1], [1, 0]])
      (array([0, 1]), array([1, 0]))
    • 上面这个例子条件中[[0,1],[1,0]]的真值为两个1,各自的第一维坐标为[0,1],第二维坐标为[1,0] 。
  • 相关阅读:
    模拟Session原理
    练手项目通讯录
    Win 8前台开发小体会
    WP自定义控件
    任务锁和自定义控件制作
    window文件复制到linux系统下
    Linux:Ubuntu配置jdk环境变量
    ubuntu 20 安装完成,配置ip信息
    Unity骨骼优化(转)
    利用栈实现简单计算器
  • 原文地址:https://www.cnblogs.com/volcao/p/9528703.html
Copyright © 2011-2022 走看看