Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing every nth element in an array

How do I remove every nth element in an array?

import numpy as np

x = np.array([0,10,27,35,44,32,56,35,87,22,47,17])
n = 3  # remove every 3rd element

...something like the opposite of x[0::n]? I've tried this, but of course it doesn't work:

for i in np.arange(0,len(x),n):
    x = np.delete(x,i)
like image 957
Medulla Oblongata Avatar asked Feb 20 '14 23:02

Medulla Oblongata


People also ask

How do I remove multiple elements from an array?

Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.

How do you remove the nth element from an array in Python?

To remove every nth element of a list in Python, utilize the Python del keyword to delete elements from the list and slicing.

Can you remove elements from an array in C#?

To delete an elements from a C# array, we will shift the elements from the position the user want the element to delete.


2 Answers

You're close... Pass the entire arange as subslice to delete instead of attempting to delete each element in turn, eg:

import numpy as np

x = np.array([0,10,27,35,44,32,56,35,87,22,47,17])
x = np.delete(x, np.arange(0, x.size, 3))
# [10 27 44 32 35 87 47 17]
like image 126
Jon Clements Avatar answered Oct 28 '22 15:10

Jon Clements


I just add another way with reshaping if the length of your array is a multiple of n:

import numpy as np

x = np.array([0,10,27,35,44,32,56,35,87,22,47,17])
x = x.reshape(-1,3)[:,1:].flatten()
# [10 27 44 32 35 87 47 17]

On my computer it runs almost twice faster than the solution with np.delete (between 1.8x and 1.9x to be honnest).

You can also easily perfom fancy operations, like m deletions each n values etc.

like image 43
Remy F Avatar answered Oct 28 '22 15:10

Remy F