4

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.

0

2 Answers 2

9

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

Comments

1
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)]

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.