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

本文介绍了numpy库中where函数的使用,以及pandas中iloc选择器的应用,通过实例讲解如何根据条件选取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
>>> ix
array([[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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值