我想在Python 3.x中用x值切割[x,y]坐标对的数组,方法与this问题的解决方案类似,但是使用坐标而不是1d列表。
例如对于(numpy)坐标数组,我想要一个像:
这样的函数coords = np.array([[1.5,10],[2.5,20],[3.5,30],[4.5,40],[5.5,50]])
def slice_coords_by_x(xmin, xmax, arr):
*some function*
slice_coords_by_x(2, 4, arr)
>>>[[2.5,20],[3.5,30]]
如果解决方案是包容性的或不包括xmin和xmax,那就不过分挑剔,因为我将在超过1000左右的大范围内使用它。
答案 0 :(得分:2)
切片并创建一个具有此类最小 - 最大限制的面具,从而选择boolean-indexing
行 -
def slice_coords_by_x(arr, xmin, xmax):
return arr[(arr[:,0] >= xmin) & (arr[:,0] <= xmax)]
样品运行 -
In [43]: arr
Out[43]:
array([[ 1.5, 10. ],
[ 2.5, 20. ],
[ 3.5, 30. ],
[ 4.5, 40. ],
[ 5.5, 50. ]])
In [44]: slice_coords_by_x(arr, xmin=2, xmax=4)
Out[44]:
array([[ 2.5, 20. ],
[ 3.5, 30. ]])
In [45]: slice_coords_by_x(arr, xmin=1, xmax=5)
Out[45]:
array([[ 1.5, 10. ],
[ 2.5, 20. ],
[ 3.5, 30. ],
[ 4.5, 40. ]])
答案 1 :(得分:2)
如果没有numpy
,您可以使用bisect
来查找插入点。请注意,该参数是一个列表(我将None
添加为here中的第二个参数,但它没有用。)
import bisect
coords = [[1.5,10],[2.5,20],[3.5,30],[4.5,40],[5.5,50]]
def slice_coords_by_x(lower,upper,arr):
l=bisect.bisect_left(arr,[lower])
u=bisect.bisect_right(arr,[upper])
return arr[l:u]
print(slice_coords_by_x(2,4,coords))
结果:
[[2.5, 20], [3.5, 30]]
bisect
要求对列表进行排序(似乎是这种情况)或者不会起作用。
答案 2 :(得分:2)
如果给定的点列表是无序的,您可以使用filter
,并使用list
实现:
def slice_coords_by_x(xmin,xmax,arr):
return list(filter(lambda p: xmin < p[0] < xmax,arr))
您也可以明确地将排序列表提供给此,但这比下一个方法花费的时间要多得多。
如果点按x坐标排序,您可以使用bisect
包:
def slice_coords_by_x(xmin,xmax,arr):
left = bisect.bisect_left(arr,[xmin])
right = bisect.bisect_right(arr,[xmax])
return arr[left:right]
答案 3 :(得分:2)
不应该
def slice_coords_by_x(xmin, xmax, arr):
return [i for i in arr if xmin <= i[0] and i[0] <= xmax]
诀窍?它可读,快速且易于访问。
此列表可以排序甚至传递数组,但该方法应该足够可访问,以便更改为任何需要。