santoku
santoku

Reputation: 3427

how to remove elements based on criteria from 3D array in python

For a 3D array like this:

import numpy as np  
m = np.random.rand(5,4,3)

What's an efficient way to remove all the elements meeting such conditions ?

m[:,:,0] > 0.5 & m[:,:,1] > 0.5 & m[:,:,2] < 0.5

Upvotes: 0

Views: 501

Answers (1)

Ron U
Ron U

Reputation: 518

Your question is still undefined but I'll answer to what I think you meant to ask. The problem with your question is that if we remove some of the elements you won't get a proper tensor (multidimensional np array) since it will have 'holes' in it. So instead of removing I'll write a way to set those values to np.nan (you can set them to whatever you'll see fit, such as -1 or None, etc...). To make it more clear, Any element from m cannot meet those three conditions at once, since they're each corresponding to different elements. Answering to your question directly will just give you the same array.

Also, it is worth mentioning that although efficiency will not cut-edge in this case, as you're going to check a condition for every value anyway, but I'll write a common numpy'ish way of doing so:

m[np.where(m[:,:,:2] > 0.5)] = np.nan
m[np.where(m[:,:,2] < 0.5)] = np.nan

What we did here is setting all values that met with a part of your condition to np.nan. This, is by creating a boolean np.array of elements that meet with a condition (the m[:,:,:2] > 0.5 part) and then with np.where check what coordination are the values which set to true. Then, with slicing to those coordination only from m, we gave them a new value with broadcasting.

Upvotes: 1

Related Questions