Home > Back-end >  Python - How to remove some terms of a numpy array in specific intervals
Python - How to remove some terms of a numpy array in specific intervals

Time:03-10

Suppose I have the following array:

import numpy as np

x = np.array([1,2,3,4,5,
              1,2,3,4,5,
              1,2,3,4,5])

How can I manipulate it to remove the term in equally spaced intervals and adapt the new length for it? For example, I'd like to have:

x = [1,2,3,4,
     1,2,3,4,
     1,2,3,4]

Where the terms from positions 4, 9, and 14 were excluded (so every 5 terms, one gets excluded). If possible, I'd like to have a code that I could use for an array with length N. Thank you in advance!

CodePudding user response:

In your case, you can simply run code below after initializing the x array(as you did your question):

x.reshape(3,5)[:,:4]

Output

array([[1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4]])

If you are interested in getting a vector and not a matrix(such as the output above), you can call the flatten function on the code above:

x.reshape(3,5)[:,:4].flatten()

Output

array([1, 2, 3, 4,
       1, 2, 3, 4,
       1, 2, 3, 4])

Explanation

Since x is a numpy array, we can use NumPy in-built functions such as reshape. This function, which has a self-explanatory name, shapes the array into the desired format. x was a vector of 15 elements. Therefore, running x.reshape(3,5) gives us a matrix with 3 rows and five columns. [:, :4] is to reselect the first four columns. flatten function changes a matrix into a vector.

CodePudding user response:

IIUC, you can use a boolean mask generated with the modulo (%) operator:

N = 5
mask = np.arange(len(x))%N != N-1
x[mask]

output: array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])

This works even if your array has not a size that is a multiple of N

  • Related