Python中numpy的where()函数
2017-11-21 15:09
435 查看
第一种用法
np.where(conditions,x,y)
if (condituons成立):
数组变x
else:
数组变y
View Code
第二种用法
where(conditions)
相当于给出数组的下标
View Code
View Code
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)
View Code
第二种用法
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)) #注意这里是坐标是前面的一维的坐标,后面是二维的坐标
View Code
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))
View Code
相关文章推荐
- Faster-R-CNN(Python).3: numpy.where()函数
- Python中numpy的where()函数
- Faster-R-CNN(Python).3: numpy.where()函数
- python: numpy-- 函数 argsort 用法
- Python基础、函数及其相关函数库(Numpy、TensorFlow)常用函数集锦(更新中,更新日期:2017-08-03)
- python科学计算_numpy_函数库
- python.numpy - array、zip 、where
- python 中 常用到的 numpy 函数 整理
- python: numpy--函数 shape用法
- python/pandas/numpy数据分析(十)-函数, rank,重复索引
- python Numpy 函数整理(一)
- python ——numpy各函数简介之生成数组函数(Array creation routines)
- python Numpy 函数整理
- Python数据分析与展示(2)——Numpy数据存取与函数
- python numpy库中的数据存取和函数
- matlab中padarray函数在numpy、python中的实现
- 【python学习笔记】18:numpy数组函数与矩阵运算
- python -- numpy 基本数据类型,算术运算,组合,分割 函数
- 【Python】Numpy扩充数组函数之repeat和tile用法
- Python引用、浅拷贝、深拷贝 和 Numpy中的视图、副本 和 Python函数参数传递