Reputation: 21
So let's say I have two arrays x and y.
x = [5, -6, 3, 11, -4, 2]
y = [1, 9, 2, 8, 12, -5]
I need to filter these arrays, keeping only values between 0 and 10. I was able to do this separately:
new_x=[i for i in x if i>=0 and i<=10]
with output
[5, 3, 2]
new_y=[i for i in y if i>=0 and i<=10]
with output
[1, 9, 2, 8]
However, these x and y arrays are meant to symbolize coordinates, which I will later have to graph. They have to remain in pairs, so if an element in the x array does not fulfill the criteria, I do not want to include the matching y element. Same goes vice versa.
By looking at the arrays, it is easy to tell that only the first and third pair - (5,1) and (3,2) respectively - fulfill my criteria. How can I filter x and y together to represent this? My dataset is much larger than this example, so I do not have the time to filter through it manually.
Any help would be greatly appreciated!
Upvotes: 1
Views: 1046
Reputation: 21
You can use the filter
function
filtered_coords = list(
filter(lambda coords: all([0 <= coord <= 10 for coord in coords]), zip(x, y))
)
If you want to split the x
and y
coordinates:
filtered_x, filtered_y = [[c[i] for c in filtered_coords] for i in range(2)]
print(filtered_x) # [5, 3]
print(filtered_y) # [1, 2]
Upvotes: 1
Reputation: 5590
zip
them together:
pairs = [(a, b) for a, b in zip(x, y) if 0 <= a <= 10 and 0 <= b <= 10]
# [(5, 1), (3, 2)]
If you then want to go back to x
, y
(I wouldn't recommend this, just keep them together), you could use:
x, y = zip(*pairs)
Which will return x
and y
as tuples:
x = (5, 3)
y = (1, 2)
In this context, the two tuples look like ordered pairs, but in general you could get something like
x = (5, 3, -6, 11, ...)
Upvotes: 3
Reputation: 1179
Use the same index to point to both arrays at the same time.
x = [5, -6, 3, 11, -4, 2]
y = [1, 9, 2, 8, 12, -5]
new_x = []
new_y = []
for i in range(len(x)):
if 0 <= x[i] <= 10 and 0 <= y[i] <= 10:
new_x.append(x[i])
new_y.append(y[i])
print(new_x, new_y)
# [5, 3] [1, 2]
Upvotes: 0