Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to select elements of an array based on values?

I'm looking for a pythonic (1-line) way to extract a range of values from an array Here's some sample code that will extract the array elements that are >2 and <8 from x,y data, and put them into a new array. Is there a way to accomplish this on a single line? The code below works but seems kludgier than it needs to be. (Note I'm actually working with floats in my application)

import numpy as np

x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])

x1 = x0[x0>2]
y1 = y0[x0>2]
x2 = x1[x1<8]
y2 = y1[x1<8]

print x2, y2

This prints

[3 3 4 5] [3 8 1 0]

Part (b) of the problem would be to extract values say 1 < x < 3 and 7 < x < 9 as well as their corresponding y values.

like image 787
Matt Wood Avatar asked Dec 24 '22 15:12

Matt Wood


2 Answers

You can chain together boolean arrays using & for element-wise logical and and | for element-wise logical or, so that the condition 2 < x0 and x0 < 8 becomes

mask = (2 < x0) & (x0 < 8)

For example,

import numpy as np

x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])

mask = (2 < x0) & (x0 < 8)
x2 = x0[mask]
y2 = y0[mask]    
print(x2, y2)
# (array([3, 3, 4, 5]), array([3, 8, 1, 0]))

mask2 = ((1 < x0) & (x0 < 3)) | ((7 < x0) & (x0 < 9))    
x3 = x0[mask2]
y3 = y0[mask2]
print(x3, y3)
# (array([8]), array([7]))
like image 128
unutbu Avatar answered Dec 28 '22 22:12

unutbu


import numpy as np

x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])
list( zip( *[(x,y) for x, y in zip(x0, y0) if 1<=x<=3 or 7<=x<=9] ) )

# [(3, 9, 8, 3), (3, 5, 7, 8)]
like image 22
Didier Trosset Avatar answered Dec 28 '22 22:12

Didier Trosset