[英]Python filter points in 2D space
I have two arrays x=[1,2,3,4]
and y=[1,0,0,1]
describing 2D points (x,y). 我有两个数组x=[1,2,3,4]
和y=[1,0,0,1]
描述2D点(x,y)。 I want to know how many elements have x>2
and y==1
. 我想知道多少元素具有x>2
和 y==1
。 What is the most simple way to do this (without any loops)? 什么是最简单的方法(没有循环)? Is it possible to do something like x[x>2]
, but for two conditions? 是否可以执行x[x>2]
,但是有两个条件?
Assuming these are numpy arrays, since your x[x>2]
is numpy syntax, you just need the and ( &
) operator: 假设这些是numpy数组,由于x[x>2]
是numpy语法,因此只需要and( &
)运算符:
meet_cond = (x > 2) & (y == 1)
how_many = meet_cond.sum()
which_x = x[meet_cond]
which_y = y[meet_cond]
If x
and y
belong together as points, you might want to pack them into a np
2D array: 如果x
和y
一起属于点,则可能要将它们打包成np
2D数组:
>>> import numpy as np
>>> x = np.array([1, 2, 3, 4])
>>> y = np.array([1, 0, 0, 1])
>>> xy = np.array([x, y]).T
>>> xy[(x > 2) & (y == 1)]
array([[4, 1]])
>>> xy[(xy[:, 0] > 2) & (xy[:, 1] == 1)]
array([[4, 1]])
>>> np.count_nonzero((xy[:, 0] > 2) & (xy[:, 1] == 1))
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.