1

My data looks like this:

all = [[-2,-1,0],[-1,-0.5,3],[-1,0.2,3],[0.2,1,3],[0.5,1,4]]

What I need to do is to select the first array which value in position [0] is bigger than zero and return me in this specific array the value of the element in position 1. I am a bit stuck, any idea? In my case it will be the array [0.2,1,3] , and in this array it should return me 1.

Viktor.w
  • 1,787
  • 2
  • 20
  • 46

2 Answers2

3

You can use next with a generator expression, then use list indexing:

res = next(x for x in all_arr if x[0] > 0)[1]  # 1

Don't use all for a variable name, this is a built-in.

If you are interested in optimizing performance with a NumPy array, see Efficiently return the index of the first value satisfying condition in array.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • I have the following error in my jupyter notebook: 'builtin_function_or_method' object is not iterable. The data were just an example.. – Viktor.w Feb 04 '19 at 10:10
  • @Viktor.w, Restart your session and *make sure you don't use any built-ins as variable names*. Use `all_` or `all_arr`, for example. – jpp Feb 04 '19 at 10:11
  • I was not precised enough in my explaination. In my original code, the array is of type numpy.ndarray – Viktor.w Feb 04 '19 at 10:20
  • @Viktor.w, My code works with a NumPy array too (you can iterate an 2d array in the same way as a list of lists). The issue is something else. – jpp Feb 04 '19 at 10:21
1

You can use the conditional masking

all_arr = np.array([[-2,-1,0],[-1,-0.5,3],[-1,0.2,3],[0.2,1,3],[0.5,1,4]])
boolean = all_arr[:,0]>0
# [False False False  True  True]

print (all_arr[boolean][0,1]) # 0 because you just need the very first occurence
# 1.0
Sheldore
  • 37,862
  • 7
  • 57
  • 71