Python3: 打印 NumPy 数组各自的 x 和 y 坐标

Python3: print respective x and y coordinate of a NumPy array

假设我有一个 Python 这样的脚本

import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [1, 5]])
x = positions[:, 0]
y = positions[:, 1]

def isInside(circle_x, circle_y, rad, x, y):
   return ((x - circle_x) ** 2 + (y - circle_y) ** 2) <= rad ** 2

circle_x = 0;
circle_y = 5;
rad = 2;

for is_inside in isInside(circle_x, circle_y, rad, x, y):
  print ("Inside" if is_inside else "Outside")

我现在还想为每个单独的“内部”或“外部”打印各自的 x 和 y 坐标。这应该是这样的

[2.5, 8] Outside, [3, 10] Outside, [0, 5] Inside, [1, 5] Inside 

我该怎么做?谁能帮帮我?

如果您有兴趣获取 x,y 坐标以及检查是在区域内还是区域外,您可以将函数更改为 return 包含 3 个值的元组:x,y, boolean.我已经编辑了您的代码并提出了以下代码:

import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [1, 5]])
x = positions[:, 0]
y = positions[:, 1]

def isInside(circle_x, circle_y, rad, x, y):
   return (x,y,((x - circle_x) ** 2 + (y - circle_y) ** 2) <= rad ** 2)

circle_x = 0;
circle_y = 5;
rad = 2;
is_inside = isInside(circle_x, circle_y, rad, x, y)
output = ""
for index in range(len(is_inside[2])):
  output += "[{x}, {y}] Inside,".format(x=is_inside[0][index], y=is_inside[1][index]) if is_inside[2][index] else "[{x}, {y}] Outside,".format(x=is_inside[0][index], y=is_inside[1][index])
print(output.strip(","))

输出

[2.5, 8.0] Outside,[3.0, 10.0] Outside,[0.0, 5.0] Inside,[1.0, 5.0] Inside

旁注:您可以使用 shapely 模块来处理地理空间结构。在这个模块中,您可以使用 within 函数检查一个点(用坐标定义)是否在一个区域(定义为多边形)中。

import numpy as np

positions = np.array([[2.5, 8], [3, 10], [0, 5], [1, 5]])

circle_centre = np.array((0, 5))
rad = 2

print(*(f"[{x}, {y}] {('Outside', 'Inside')[is_inside]}"
        for x, y, is_inside in zip(*np.transpose(positions), ((positions - circle_centre) ** 2).sum(1) <= rad ** 2)),
      sep=", ")