I have a numpy array in this form:
n = [[[5 0 2]
[8 9 7]
[2 2 2]
[5 9 5] <-- target value
[4 1 5]]
[[5 3 9]
[4 2 7]
[7 0 7]
[4 9 6] <-- target value
[3 8 5]]]
I want to get all the values except the 3rd row from each individual array. ie. the results should be in this way:
[[[5 0 2]
[8 9 7]
[2 2 2]
[4 1 5]]
[[5 3 9]
[4 2 7]
[7 0 7]
[3 8 5]]]
I tried using indexing, but I cannot achieve it. I have a large numpy array where this operation needs to be done. Is there any efficient method to do it, other than making a copy of it and removing it using delete method. Also, I don't want to utilize much space by creating a copy, I just want to use indexing to ignore the particular column for a while.
CodePudding user response:
You can use numpy.delete(arr, index, axis)
like below:
>>> n
array([[[5, 0, 2],
[8, 9, 7],
[2, 2, 2],
[5, 9, 5],
[4, 1, 5]],
[[5, 3, 9],
[4, 2, 7],
[7, 0, 7],
[4, 9, 6],
[3, 8, 5]]])
>>> np.delete(n, 3, 1)
array([[[5, 0, 2],
[8, 9, 7],
[2, 2, 2],
[4, 1, 5]],
[[5, 3, 9],
[4, 2, 7],
[7, 0, 7],
[3, 8, 5]]])
Update: without delete
:
>>> msk = (0,1,2,4)
>>> n[:,msk,:]
CodePudding user response:
You can create a list of selected elements, popping the target one:
import numpy as np
n = np.array([[[5,0,2],
[8,9,7],
[2,2,2],
[5,9,5],
[4,1,5]],
[[5,3,9],
[4,2,7],
[7,0,7],
[4,9,6],
[3,8,5]]])
target_element = 3
s = list(range(len(n[0])))
s.pop(target_element)
print(n[:,s])
or
s = list(range(len(n[0])))
print(n[:,s[:target_element] s[target_element 1:]])