1

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() or array[cond]. Since you know, this is Python B)

NOTE: The reason why I want to do this is because I have a random subset of the Y values and I want to find the corresponding X values.

2
  • Are the values in y unique? Commented May 10, 2016 at 17:09
  • yes each of the y values are unique Commented May 10, 2016 at 17:10

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

5 Comments

Looks great, testing this now. Does this or a similar method generalize to 2d arrays? (PS: I wish I could double thumb up thing!)
@SARose So, for 2D arrays, you need to decide if by "==" do you mean all elements in a row or any one element in a row, assuming you would like a row based comparison. If you are really looking to extend this to 2D, it might be a good idea to post a sample case in the question or post a new question altogether, because it won't be a straight forward extension.
Okay I'll post a sample case. But yeah I do want all the elements in one row from one array to match all the elements in one row from another array.
@SARose So, a quick way with broadcasting for 2D case, would be : R,C = np.where((random_y[:,None] == y).all(2)). Then x[C] and random_y[R] would be the outputs just as listed for 1D solution. Not a great deal of change there! :)
@SARose Likewise for tolerance, you can use R,C = np.where((np.abs(random_y[:,None] - y) <= tol).all(2)) keeping rest the same.
0

Maybe this could do the trick(not tested):

print(Str(x[np.where(y == iy)]) + " " + Str(iy) + "\n") for iy in random_y

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.