SARose - 11 months ago 93

Python Question

I don't know how to describe this well so I'll just show it.

How do I do this...

`for iy in random_y:`

print(x[np.where(y == iy)], iy)

X y

[ 0.5] : 0.247403959255

[ 2.] : 0.841470984808

[ 49.5]: -0.373464754784

without for loops and I get a solution as a single array like when you use

`np.where()`

`array[cond]`

Answer

If you are looking for exact matches, you can simply use `np.in1d`

as this is a perfect scenario for its usage, like so -

```
first_output = x[np.in1d(y,random_y)]
second_output = random_y[np.in1d(random_y,y)
```

If you are dealing with floating-point numbers, you might want to use some tolerance factor into the comparisons. So, for such cases, you can use `NumPy broadcasting`

and then use `np.where`

, like so -

```
tol = 1e-5 # Edit this to change tolerance
R,C = np.where(np.abs(random_y[:,None] - y)<=tol)
first_output = x[C]
second_output = random_y[R]
```