Home > front end >  Python3: print respective x and y coordinate of a NumPy array
Python3: print respective x and y coordinate of a NumPy array

Time:02-26

Let's say I have a Python script like that

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

I now want to print the respective x and y coordinates also for each individual "Inside" or "Outside". This should look like this

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

How can I do this? Can anyone help me out?

CodePudding user response:

If you are interested in getting the x,y coordinates as well as checking to be inside or outside of the area, you can change your function to return a tuple that contains 3 values: x,y, boolean. I have edited your code and come up with the code below:

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

Output

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

A side note: You can use shapely module in order to work with geospatial structures. In this module, you can check whether a point (defined with coordinates) is in a area (defines as polygon) using within function.

CodePudding user response:

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=", ")
  • Related