详解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搭建Django应用程序步骤及版本冲突问题解决
Nov 19 Python
python 简单的多线程链接实现代码
Aug 28 Python
对变量赋值的理解--Pyton中让两个值互换的实现方法
Nov 29 Python
Python中Proxypool库的安装与配置
Oct 19 Python
pandas 空的dataframe 插入列名的示例
Oct 30 Python
python列表使用实现名字管理系统
Jan 30 Python
Python定义函数实现累计求和操作
May 03 Python
使用python采集Excel表中某一格数据
May 14 Python
浅谈cv2.imread()和keras.preprocessing中的image.load_img()区别
Jun 12 Python
2021年的Python 时间轴和即将推出的功能详解
Jul 27 Python
Python grequests模块使用场景及代码实例
Aug 10 Python
Python解析m3u8拼接下载mp4视频文件的示例代码
Mar 03 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
PHP base64+gzinflate压缩编码和解码代码
2008/10/03 PHP
php面向对象全攻略 (十六) 对象的串行化
2009/09/30 PHP
php删除数组元素示例分享
2014/02/17 PHP
php实现可运算的验证码
2015/11/10 PHP
php可变长参数处理函数详解
2017/02/22 PHP
Javascript 更新 JavaScript 数组的 uniq 方法
2008/01/23 Javascript
jquery.ajax的url中传递中文乱码问题的解决方法
2014/02/07 Javascript
jQuery遍历之next()、nextAll()方法使用实例
2014/11/08 Javascript
浅谈javascript中关于日期和时间的基础知识
2016/07/13 Javascript
bootstrap下拉列表与输入框组结合的样式调整
2016/10/08 Javascript
完美解决jQuery 鼠标快速滑过后,会执行多次滑出的问题
2016/12/08 Javascript
使用 NodeJS+Express 开发服务端的简单介绍
2017/04/07 NodeJs
node.js中debug模块的简单介绍与使用
2017/04/25 Javascript
vue 2.0路由之路由嵌套示例详解
2017/05/08 Javascript
JS FormData上传文件的设置方法
2017/07/05 Javascript
页面缩放兼容性处理方法(zoom,Firefox火狐浏览器)
2017/08/29 Javascript
浅谈在vue项目中如何定义全局变量和全局函数
2017/10/24 Javascript
React Native 通告消息竖向轮播组件的封装
2020/08/25 Javascript
Vue shopCart 组件开发详解
2018/01/26 Javascript
Angular使用动态加载组件方法实现Dialog的示例
2018/05/11 Javascript
VUE 实现动态给对象增加属性,并触发视图更新操作示例
2019/11/29 Javascript
JavaScript简易计算器制作
2020/01/17 Javascript
vue style width a href动态拼接问题的解决
2020/08/07 Javascript
js实现点击烟花特效
2020/10/14 Javascript
分析Python编程时利用wxPython来支持多线程的方法
2015/04/07 Python
Python实现的拟合二元一次函数功能示例【基于scipy模块】
2018/05/15 Python
Win系统PyQt5安装和使用教程
2019/12/25 Python
Pandas时间序列:重采样及频率转换方式
2019/12/26 Python
一款纯css3实现的响应式导航
2014/10/31 HTML / CSS
世界上最具创新性的增强型知名运动品牌:Proviz
2018/04/03 全球购物
Beauty Expert美国/加拿大:购买奢侈美容产品
2018/12/05 全球购物
优纳科技软件测试面试题
2012/05/15 面试题
学习委员自我鉴定
2014/01/13 职场文书
技校学生个人职业生涯规划范文
2014/03/03 职场文书
售后求职信范文
2014/03/15 职场文书
追悼会答谢词
2015/01/05 职场文书