根据条件选择多个行 [英] Numpy select rows based on condition

查看:101
本文介绍了根据条件选择多个行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用numpy从二维数组中删除行,其中该行的第一个值(因此索引为0的元素)与特定条件不匹配.

I'm trying to use numpy to remove rows from a two dimensional array where the first value of the row (so the element at index 0) does not match a certain condition.

我能够使用两个循环使用常规python来执行此操作,但是我想使用numpy来更有效地执行此操作,例如与 numpy.where

I am able to do this with regular python using two loops, but I would like to do it more efficiently with numpy, e.g. with numpy.where

我一直在尝试使用 numpy.where numpy.delete 进行各种操作,但是我很难通过使用仅需要一个条件来选择行的事实由第一个元素而不是第二个元素验证(我不在乎第二个元素的值)

I have been trying various things with numpy.where and numpy.delete but I struggle with the fact that I want to select rows by using a condition that only needs to be verified by the first element, and not the second (I dont care about the value of the second element)

这里是一个示例,其中我只想保留每行的第一个值为6的行.

Here is an example where I only want to keep the rows where the first value of each row is 6.

输入:

[[0,4],
[0,5],
[3,5],
[6,8],
[9,1],
[6,1]]

输出:

[[6,8],
[6,1]]

推荐答案

使用布尔掩码:

mask = z[:, 0] == 6
z[mask, :]

这比 np.where 效率高得多,因为您可以直接使用布尔掩码,而无需先将其转换为索引数组的开销.

This is much more efficient than np.where because you can use the boolean mask directly, without having the overhead of converting it to an array of indices first.

一个班轮:

z[z[:,0]==6, :]

这篇关于根据条件选择多个行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆