详解Python中where()函数的用法


Posted in Python onMarch 27, 2018

where()的用法

首先强调一下,where()函数对于不同的输入,返回的只是不同的。

1当数组是一维数组时,返回的值是一维的索引,所以只有一组索引数组

2当数组是二维数组时,满足条件的数组值返回的是值的位置索引,因此会有两组索引数组来表示值的位置

例如

>>>b=np.arange(10)
>>>b
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>np.where(b>5)
 (array([6, 7, 8, 9], dtype=int64),)

>>>a=np.reshape(np.arange(20),(4,5))
>>>a 
array([[ 0, 1, 2, 3, 4],
    [ 5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19]])
>>>np.where(a>10)
(array([2, 2, 2, 2, 3, 3, 3, 3, 3], dtype=int64),
 array([1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=int64))

对numpy标准库里的解释做一个介绍:

numpy.where(condition[, x, y])

基于条件condition,返回值来自x或者y.

如果.

参数: condition : 数组,bool值 When True, yield x, otherwise yield y. x, y : array_like, 可选 x与y的shape要相同,当condition中的值是true时返回x对应位置的值,false是返回y的
返回值: out : ndarray or tuple of ndarrays ①如果参数有condition,x和y,它们三个参数的shape是相同的。那么,当condition中的值是true时返回x对应位置的值,false是返回y的。 ②如果参数只有condition的话,返回值是condition中元素值为true的位置索引,切是以元组形式返回,元组的元素是ndarray数组,表示位置的索引
>>> np.where([[True, False], [True, True]],
...     [[1, 2], [3, 4]],
...     [[9, 8], [7, 6]])
array([[1, 8],
    [3, 4]])
>>>
>>> np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))
>>>
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 3.0 )]        # Note: result is 1D.
array([ 4., 5., 6., 7., 8.])
>>> np.where(x < 5, x, -1)        # Note: broadcasting.
array([[ 0., 1., 2.],
    [ 3., 4., -1.],
    [-1., -1., -1.]])
Find the indices of elements of x that are in goodvalues.

>>>
>>> goodvalues = [3, 4, 7]
>>> ix = np.in1d(x.ravel(), goodvalues).reshape(x.shape)
>>> ix
array([[False, False, False],
    [ True, True, False],
    [False, True, False]], dtype=bool)
>>> np.where(ix)
(array([1, 1, 2]), array([0, 1, 1]))

两种方法的示例代码

第一种用法

np.where(conditions,x,y)

if (condituons成立):

数组变x

else:

数组变y

import numpy as np
'''
x = np.random.randn(4,4)
print(np.where(x>0,2,-2))
#试试效果
xarr = np.array([1.1,1.2,1.3,1.4,1.5])
yarr = np.array([2.1,2.2,2.3,2.4,2.5])
zarr = np.array([True,False,True,True,False])
result = [(x if c else y)
     for x,y,c in zip(xarr,yarr,zarr)]
print(result)

#where()函数处理就相当于上面那种方案

result = np.where(zarr,xarr,yarr)
print(result)

'''
#发现个有趣的东西
# #处理2组数组
# #True and True = 0
# #True and False = 1
# #False and True = 2
# #False and False = 3

cond2 = np.array([True,False,True,False])
cond1 = np.array([True,True,False,False])
#第一种处理 太长太丑
result = []
for i in range(4):
  if (cond1[i] & cond2[i]):  result.append(0);
  elif (cond1[i]):  result.append(1);
  elif (cond2[i]):  result.append(2);
  else : result.append(3);
print(result)
#第二种 直接where() 很快很方便
result = np.where(cond1 & cond2,0,np.where(cond1,1,np.where(cond2,2,3)))
print(result)
#第三种 更简便(好像这跟where()函数半毛钱的关系都没有
result = 1*(cond1 & -cond2)+2*(cond2 & -cond1)+3*(-(cond1 | cond2)) (没想到还可以这么表达吧)
print(result)

第二种用法

where(conditions)

相当于给出数组的下标

x = np.arange(16)
print(x[np.where(x>5)])
#输出:(array([ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], dtype=int64),)

x = np.arange(16).reshape(-1,4)
print(np.where(x>5))

#(array([1, 1, 2, 2, 2, 2, 3, 3, 3, 3], dtype=int64), array([2, 3, 0, 1, 2, 3, 0, 1, 2, 3], dtype=int64))
#注意这里是坐标是前面的一维的坐标,后面是二维的坐标
ix = np.array([[False, False, False],
    [ True, True, False],
    [False, True, False]], dtype=bool)
print(np.where(ix))
#输出:(array([1, 1, 2], dtype=int64), array([0, 1, 1], dtype=int64))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 列表list使用介绍
Nov 30 Python
python实现汉诺塔递归算法经典案例
Mar 01 Python
Python logging管理不同级别log打印和存储实例
Jan 19 Python
使用 Python 实现文件递归遍历的三种方式
Jul 18 Python
Python 存储字符串时节省空间的方法
Apr 23 Python
python实现图片转字符小工具
Apr 30 Python
python 返回一个列表中第二大的数方法
Jul 09 Python
Python数据可视化实现多种图例代码详解
Jul 14 Python
Python读取Excel一列并计算所有对象出现次数的方法
Sep 04 Python
selenium学习教程之定位以及切换frame(iframe)
Jan 04 Python
pytorch损失反向传播后梯度为none的问题
May 12 Python
Python 可迭代对象 iterable的具体使用
Aug 07 Python
Django基于ORM操作数据库的方法详解
Mar 27 #Python
利用Python批量提取Win10锁屏壁纸实战教程
Mar 27 #Python
Django学习笔记之ORM基础教程
Mar 27 #Python
Python使用xlwt模块操作Excel的方法详解
Mar 27 #Python
Python安装图文教程 Pycharm安装教程
Mar 27 #Python
python 接口返回的json字符串实例
Mar 27 #Python
使用Django和Python创建Json response的方法
Mar 26 #Python
You might like
丧钟首部独立剧集《丧钟:骑士与龙》北美正式开播,场面血腥
2020/04/09 欧美动漫
PHP日期时间函数的高级应用技巧
2009/05/16 PHP
Php Mssql操作简单封装支持存储过程
2009/12/11 PHP
PHP 图片水印类代码
2012/08/27 PHP
PHP基于DOMDocument解析和生成xml的方法分析
2017/07/17 PHP
uploadify在Firefox下丢失session问题的解决方法
2013/08/07 Javascript
js字符串转成JSON
2013/11/07 Javascript
js控制表单不能输入空格的小例子
2013/11/20 Javascript
浅析jQuery1.8的几个小变化
2013/12/10 Javascript
jQuery处理json数据返回数组和输出的方法
2015/03/11 Javascript
用JS生成UUID的方法实例
2016/03/30 Javascript
BootStrap日期控件在模态框中选择时间下拉菜单无效的原因及解决办法(火狐下不能点击)
2016/08/18 Javascript
Vue.js 和 MVVM 的注意事项
2016/11/07 Javascript
微信小程序 picker-view 组件详解及简单实例
2017/01/10 Javascript
利用JS实现简单的日期选择插件
2017/01/23 Javascript
Vue.js仿微信聊天窗口展示组件功能
2017/08/11 Javascript
解决Mac安装thrift因bison报错的问题
2018/05/17 Javascript
详解如何在微信小程序开发中正确的使用vant ui组件
2018/09/13 Javascript
Vue 报错TypeError: this.$set is not a function 的解决方法
2018/12/17 Javascript
详解NodeJs项目 CentOs linux服务器线上部署
2019/09/16 NodeJs
javascript实现点击星星小游戏
2019/12/24 Javascript
python实现京东秒杀功能
2018/07/30 Python
基于python判断目录或者文件代码实例
2019/11/29 Python
python实现双人五子棋(终端版)
2020/12/30 Python
Zavvi美国:英国娱乐之家
2017/03/19 全球购物
C++的几个面试题附答案
2016/08/03 面试题
中专生自我鉴定
2013/12/17 职场文书
大学同学会活动方案
2014/08/20 职场文书
革命英雄事迹演讲稿
2014/09/13 职场文书
工作骂脏话检讨书
2014/10/05 职场文书
原料仓管员岗位职责
2015/04/01 职场文书
村主任当选感言
2015/08/01 职场文书
优秀学生干部主要事迹材料
2015/11/04 职场文书
mysql下的max_allowed_packet参数设置详解
2022/02/12 MySQL
JS中forEach()、map()、every()、some()和filter()的用法
2022/05/11 Javascript
mysql函数之截取字符串的实现
2022/08/14 MySQL