3

I would like to select the x, y values from an array of the same, for example :

xy = [[0.0, 3], [0.1, 1], [0.2, -1]]

where y > 0, so the output should be

array[ [0.0, 3], [0.1, 1]]

I tried something like

[x for x in xy if y>0]

, but it returns the following error :

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

2
  • Don't you mean >= 0? Commented Nov 28, 2016 at 15:36
  • @Simon : I suppose your issue is resolved, please mark the answer accepted. :) Commented Nov 29, 2016 at 2:43

4 Answers 4

2

slice the object to compare just the y values and use the resulting boolean mask:

In [12]:
xy[xy[:,1]>0]

Out[12]:
array([[ 0. ,  3. ],
       [ 0.1,  1. ]])

Here xy[:,1] gives you just the y values:

In [13]:
xy[:,1]

Out[13]:
array([ 3.,  1., -1.])

Here is the resultant boolean mask:

In [14]:
xy[:,1] > 0

Out[14]:
array([ True,  True, False], dtype=bool)
Sign up to request clarification or add additional context in comments.

Comments

2

Try this :

ans = [i for i in xy if i[1] > 0]

Output :

[[0.0, 3], [0.1, 1]]

5 Comments

or [[x, y] for x, y in xy if y > 0]
Thank you, this works but leaves me with a list of arrays.
What is your expected output ? @Simon
In the end, I want to fit the y-values using fit_curve, so before I was converting the 2D array into 1D arrays x and y using [:,0] and [:,1]
You can do this : numpy.array(ans).flatten() , if you want a single list.
1

Another approach using itertools.compress:

from itertools import compress

xy = [[0.0, 3], [0.1, 1], [0.2, -1]]
res = compress(xy, [item[1] > 0 for item in xy])

Output:

>>> list(res)
[[0.0, 3], [0.1, 1]]

Comments

0

try this:

[x for x in xy if x[1]>0]

1 Comment

this answer is the same as Jarvis' answer

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.