0

I've got a question regarding python magic. I have to arrays the same size. One filled with points and the other is a boolean array (true|false). Now I want to delete all points from the first array where the element is false in the other array.

So if my first array is [(1,2), (2,3), (3,4), (4,5)] and the other array is [true, false, false, true] the result array shall be [(1,2), (4,5)].

The problem is, that the arrays are quite big and the iterative method is pretty slow.

Does someone knows some numpy magic to execute this task pythonesque?

2
  • 2
    Use the bool array as the index? first_array[bool_array] Commented Jan 15, 2018 at 14:01
  • Your 1st "array" looks like a list of tuples, not a Numpy array. And you should use False and True for boolean values. Commented Jan 15, 2018 at 14:02

2 Answers 2

3

it's straightforward with numpy

# convert your arrays to ndarrays
a = np.array([(1, 2), (2, 3), (3, 4), (4, 5)])
mask = np.array([True, False, False, True])

print a[mask].tolist()
# [[1, 2], [4, 5]]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution. Whats about the performance? Does it do the same like iterating over the elements?
I've made some tests with your example, and it seems that it's 3 times SLOWER than the list comprehension solution.
0

Just take what you want , don't delete it: , One line solution without any external lib

print([first_1[i] for i,j in enumerate(second_1) if j==True])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.