numpy中where的使用和pandas中iloc的使用

来源:互联网 发布:安卓软件免费源码 编辑:程序博客网 时间:2024/06/03 21:16

1.numpy中where的使用

numpy.where

numpy.where(condition[xy])

根据条件,从xy返回元素。

如果只给出条件,则返回condition.nonzero()

参数:

condition:array_like,bool

当为True时,产量x,否则产生y

x,y:array_like,可选

要选择的值。xy需要具有与条件相同的形状。

返回:

out:ndarray的数组或元组

如果指定xy,则输出数组包含x的元素,其中条件y

如果仅给出条件,则返回元组condition.nonzero(),其中条件为True。

也可以看看

nonzerochoose

笔记

如果给定xy且输入数组是1-D,where等效于:

[xv if c else yv for (c,xv,yv) in zip(condition,x,y)]

例子

>>> 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.]])

查找良好值x元素的索引。

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

http://python.usyiyi.cn/translate/Pandas_0j2/index.html




原创粉丝点击