1

I have an array as depicted below. How can I remove the last two elements, e.g. 3,4,7,8,11,12,15,16,19 and 20 ?

import numpy as np

vector = np.arange(1,21)

vector2 = np.array_split(vector,5)

print(vector2)

[array([1, 2, 3, 4]),
 array([5, 6, 7, 8]),
 array([ 9, 10, 11, 12]),
 array([13, 14, 15, 16]),
 array([17, 18, 19, 20])]

Would indexing directly be the only method or is there perhaps a better approach to doing this?

user4933
  • 1,485
  • 3
  • 24
  • 42
  • Does this answer your question? [How to remove specific elements in a numpy array](https://stackoverflow.com/questions/10996140/how-to-remove-specific-elements-in-a-numpy-array) – CoolCoder May 04 '21 at 01:45
  • Hi @CoolCoder , no it does not it is similar but I do not want to index values through providing the specific position to delete. I would like to provide a constant value that leads a specific number of the last numbers to be deleted, whilst keeping the matrix in a similar number of dimensions. – user4933 May 04 '21 at 01:52

1 Answers1

0

Assume vector length is always a multiple of 5, you can use reshape instead of array_split to convert the vector into a (5, 4) array and then use normal array indexing to remove the last two columns:

vector.reshape(5, -1)[:, :-2]

#[[ 1  2]
# [ 5  6]
# [ 9 10]
# [13 14]
# [17 18]]

If the assumption doesn't hold, then you'll have to loop through the result and remove elements from each sub array since array_split produces a list:

vector2 = np.array_split(vector,5)
[x[:-2] for x in vector2]

#  [array([1, 2]), array([5, 6]), array([ 9, 10]), array([13, 14]), array([17, 18])]
Psidom
  • 209,562
  • 33
  • 339
  • 356