详解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 Web服务器Tornado使用小结
May 06 Python
python中对list去重的多种方法
Sep 18 Python
基于Python实现的ID3决策树功能示例
Jan 02 Python
Python numpy 提取矩阵的某一行或某一列的实例
Apr 03 Python
Python基于更相减损术实现求解最大公约数的方法
Apr 04 Python
对python中的iter()函数与next()函数详解
Oct 18 Python
如何使用python把ppt转换成pdf
Jun 29 Python
python3实现从kafka获取数据,并解析为json格式,写入到mysql中
Dec 23 Python
解决使用python print打印函数返回值多一个None的问题
Apr 09 Python
keras中epoch,batch,loss,val_loss用法说明
Jul 02 Python
Python使用MapReduce进行简单的销售统计
Apr 22 Python
python 单机五子棋对战游戏
Apr 28 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 Mysql日期和时间函数集合
2007/11/16 PHP
PHP使用PHPexcel导入导出数据的方法
2015/11/14 PHP
PHP共享内存用法实例分析
2016/02/12 PHP
javascript笔试题目附答案@20081025_jb51.net
2008/10/26 Javascript
jquery 读取页面load get post ajax 四种方式代码写法
2011/04/02 Javascript
最短的javascript:地址栏载入脚本代码
2011/10/13 Javascript
js中直接声明一个对象的方法
2014/08/10 Javascript
JS学习之表格的排序简单实例
2016/05/16 Javascript
浅谈js中的三种继承方式及其优缺点
2016/08/10 Javascript
Jquery实现跨域异步上传文件总结
2017/02/03 Javascript
详解Vue使用 vue-cli 搭建项目
2017/04/20 Javascript
JavaScript运动框架 多值运动(四)
2017/05/18 Javascript
JavaScript设计模式之策略模式详解
2017/06/09 Javascript
jQuery Easyui Treegrid实现显示checkbox功能
2017/08/08 jQuery
JS处理一些简单计算题
2018/02/24 Javascript
在vue中把含有html标签转为html渲染页面的实例
2019/10/28 Javascript
微信小程序实现音乐播放器
2019/11/20 Javascript
[52:05]EG vs OG 2019国际邀请赛小组赛 BO2 第二场 8.16
2019/08/18 DOTA
用python实现百度翻译的示例代码
2018/03/09 Python
python删除某个字符
2018/03/19 Python
Python3+django2.0+apache2+ubuntu14部署网站上线的方法
2018/07/07 Python
Django中的cookie和session
2019/08/27 Python
Python Django view 两种return的实现方式
2020/03/16 Python
Windows 平台做 Python 开发的最佳组合(推荐)
2020/07/27 Python
python实现取余操作的简单实例
2020/08/16 Python
用python进行视频剪辑
2020/11/02 Python
Pat McGrath Labs官网:世界上最有影响力的化妆师推出的彩妆品牌
2018/01/07 全球购物
remote接口和home接口主要作用
2013/05/15 面试题
建龙钢铁面试总结
2014/04/15 面试题
活动总结怎么写
2014/04/28 职场文书
乡镇保密工作责任书
2014/07/28 职场文书
群众路线教育实践活动实施方案
2014/10/31 职场文书
离婚起诉书范文2015
2015/05/19 职场文书
认识实习感想
2015/08/10 职场文书
Python机器学习之底层实现KNN
2021/06/20 Python
为什么RedisCluster设计成16384个槽
2021/09/25 Redis