numpy.where()方法不和其他方法类似,从结果就能看到方法功能,需要琢磨一番才能够理解它。
1.语法
numpy.where(condition[,x,y])
返回:ndarray 或者 tuple of ndarrays = (array_row, array_col)
2.思路
if condition == True:
取x中当前位置的数值(如果没有x,取True在矩阵中的索引[row, rol])
else:
取y中当前位置的数值
3.剖析numpy.where(cond, x, y)
一般用最简单的例子最容易理解核心思想。
>>> print numpy.where([[True, False]], [[1,2]], [[3,4]])
[[1 4]]
>>>
从上可知condition = [[True, Flase]],x = [[1, 2]], y = [[3, 4]]
1)where()计算结果是啥?
简单理解为,得到和condition相同shape的ndarray,ret = [[a, b]],即condition.shape == ret.shape
2)结果[[a, b]]中a和b怎么得到?
首先:where会根据condition=[[True, False]]来计算[[a, b]]的数值,即用True计算a,用False计算b
其次:a,b一定来自x和y
并且:a是x中的1或者y中的3,b是x中的2或者y中的4
按照如下规则确定a的取值:
if conditon中a所在位置是True:
a = x[[1, 2]]中的1,而不是y[[3, 4]]中的3
else:
a = y[[3,4]]中的3,而不是x[[1, 2]]中的1
根据condition=[[True, Flase]]可知a = x[[1, 2]]中的1
按照如下规则确定b的取值:
if condition中b所在位置是False:
b = x[[1, 2]]中2,而不是y[[3, 4]]中的4
else:
b = y[[3, 4]]中的4,而不是x[[1, 2]]中的2
根据condition=[[True, Flase]]可知b = y[[3, 4]]中的4
综上所述:numpy.where([[True, False]], [[1,2]], [[3,4]])的结果就是[[1, 4]]
4.剖析numpy.where(condition)
还是一样,最简单的例子最容易理解核心思想,设condition=[[True, Flase]]
则表示numpy.where([[True, False]])返回True在矩阵中的索引,执行的结果如下所示:
>>> print numpy.where(numpy.mat([[True, False]]))
(array([0], dtype=int64), array([0], dtype=int64))
>>>
在理解numpy.where([[True, False]])之前,先理解矩阵中的每个元素索引。
4.1理解矩阵中元素的索引[row, col]
>>> print numpy.mat([[1,2],[3,4]])
[[1 2]
[3 4]]
>>> numpy.mat([[1,2], [3,4]])[0, 0]
1
>>> numpy.mat([[1,2], [3,4]])[0, 1]
2
>>> numpy.mat([[1,2], [3,4]])[1, 0]
3
>>> numpy.mat([[1,2], [3,4]])[1, 1]
4
>>>
可以知道在[[1,2],[3,4]]矩阵中,有4个元素,每个元素的索引是:
1----[0, 0] 2----[0, 1]
3----[1, 0] 4----[1, 1]
为了容易理解一个元素的索引结构,用[row, col]来表示索引,其中row是元素所在行号,col是元素所在列号,如:
1----[0, 0],表示元素1在矩阵的第1行和第1列的位置
2----[0, 1],表示元素2在矩阵的第1行和第2列的位置
3----[1, 0],表示元素3在矩阵的第2行和第1列的位置
4----[1, 1],表示元素4在矩阵的第