Python3:通过一个函数循环一个numpy数组

Python3: Loop a numpy array through a function

假设我有一个像这样的 numpy 数组 (positions_full),它加载一些坐标数据,如 2.5 或 8.2。我现在想通过 def isInside 循环该数组。我该怎么做?

positions_full = np.loadtxt('positions.txt')

x = positions_full[:,0]

y = positions_full[:,1]  

def isInside(circle_x, circle_y, rad, x, y):

    if ((x - circle_x) * (x - circle_x) +

        (y - circle_y) * (y - circle_y) <= rad * rad):

        return True;

    else:

        return False;


x = 2.5

y = 8.2

circle_x = 0;

circle_y = 5;

rad = 2;

if(isInside(circle_x, circle_y, rad, x, y)):

    print(x,y,rad,"Inside");

else:

    print(x,y,rad,"Outside");

我觉得还是用numpy的vectorization比较好。您可以使函数 isInside 到 return 成为 numpy 布尔值数组 。然后你可以用一个普通的 for-loop 在函数外循环。像这样:

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")