You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Answer from behzad.nouri on Stack Overflow
๐ŸŒ
Data Science Parichay
datascienceparichay.com โ€บ home โ€บ blog โ€บ numpy โ€“ get every nth element in array
Numpy - Get Every Nth Element in Array - Data Science Parichay
August 11, 2022 - You can use slicing to get every nth element of a Numpy array. Slice the array from its start to end and use n as the step parameter.
Top answer
1 of 2
259

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

2 of 2
2

Complementary to behzad.nouri's answer: If you want to control the number of final elements and ensure it's always fixed to a predefined value (rather than controlling a fixed step in between subsamples) you can use numpy's linspace method followed by integer rounding.

For example, with num_elements=4:

>>> a
array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> choice = np.round(np.linspace(1, len(a)-1, num=4)).astype(int)
>>> a[choice]
array([ 2,  5,  7, 10])

Or, subsampling an array with final start/end points in general:

>>> import numpy as np
>>> np.round(np.linspace(0, len(a)-1, num=4)).astype(int)
array([0, 3, 6, 9])
>>> np.round(np.linspace(0, len(a)-1, num=15)).astype(int)
array([0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9])
Discussions

assigning every Nth element in a list in python - Stack Overflow
I want to set every Nth element in a list to something else. (Like this question which is for Matlab.) Here's an attempt with N=2: >>> x=['#%d' % i for i in range(10)] >>> x [... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Numpy: Replace every n element in the first half of an array - Stack Overflow
If I have a numpy array and want to replace every nth element to 0 in the first half of the array( no change in the second half), how can I do this efficiently? Now my code is not efficient enough:... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Skip every nth index of numpy array - Stack Overflow
In order to do K-fold validation I would like to use slice a numpy array such that a view of the original array is made but with every nth element removed. For example: [0, 1, 2, 3, 4, 5, 6, 7, 8, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 2, 2016
When wanting to select every Nth element while iterating through an array, is it more 'pythonic' to use slice notation or the modulo operator?
I'd go with this: for x in range(0, 100, 20): More on reddit.com
๐ŸŒ r/learnpython
2
2
March 9, 2021
๐ŸŒ
Finxter
blog.finxter.com โ€บ 5-best-ways-to-extract-every-nth-element-from-a-numpy-array
5 Best Ways to Extract Every Nth Element from a NumPy Array โ€“ Be on the Right Side of Change
This code snippet creates an array ... 5th element. Itโ€™s direct and efficient since NumPy slicing operates at a low level. Another method involves creating an index array with np.arange(start, stop, n) and using it for fancy indexing. ... This code creates an index array to extract every nth ...
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-skip-every-nth-index-of-numpy-array
How to skip every Nth index of NumPy array ? - GeeksforGeeks
December 26, 2023 - A counter can be maintained to keep a count of the elements traversed so far, and then as soon as the Nth position is encountered, the element is skipped and the counter is reset to 0. All the elements are appended to a new list excluding the Nth index element encountered while traversal. ... # importing required packages import numpy as np # declaring a numpy array x = np.array([1.2, 3.0, 6.7, 8.7, 8.2, 1.3, 4.5, 6.5, 1.2, 3.0, 6.7, 8.7, 8.2, 1.3, 4.5, 6.5]) # skipping every 4th element n = 4 # declaring new list new_arr = [] cntr = 0 # looping over array for i in x: if(cntr % n != 0): new_arr.append(i) # incrementing counter cntr += 1 print("Array after skipping nth element") print(new_arr)
Top answer
1 of 3
13

Approach #1 with modulus

a[np.mod(np.arange(a.size),4)!=0]

Sample run -

In [255]: a
Out[255]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [256]: a[np.mod(np.arange(a.size),4)!=0]
Out[256]: array([1, 2, 3, 5, 6, 7, 9])

Approach #2 with masking : Requirement as a view

Considering the views requirement, if the idea is to save on memory, we could store the equivalent boolean array that would occupy 8 times less memory on Linux system. Thus, such a mask based approach would be like so -

# Create mask
mask = np.ones(a.size, dtype=bool)
mask[::4] = 0

Here's the memory requirement stat -

In [311]: mask.itemsize
Out[311]: 1

In [312]: a.itemsize
Out[312]: 8

Then, we could use boolean-indexing as a view -

In [313]: a
Out[313]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [314]: a[mask] = 10

In [315]: a
Out[315]: array([ 0, 10, 10, 10,  4, 10, 10, 10,  8, 10])

Approach #3 with NumPy array strides : Requirement as a view

You can use np.lib.stride_tricks.as_strided to create such a view given the length of the input array is a multiple of n. If it's not a multiple, it would still work, but won't be a safe practice, as we would be going beyond the memory allocated for input array. Please note that the view thus created would be 2D.

Thus, an implementaion to get such a view would be -

def skipped_view(a, n):
    s = a.strides[0]
    strided = np.lib.stride_tricks.as_strided
    return strided(a,shape=((a.size+n-1)//n,n),strides=(n*s,s))[:,1:]

Sample run -

In [50]: a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # Input array

In [51]: a_out = skipped_view(a, 4)

In [52]: a_out
Out[52]: 
array([[ 1,  2,  3],
       [ 5,  6,  7],
       [ 9, 10, 11]])

In [53]: a_out[:] = 100 # Let's prove output is a view indeed

In [54]: a
Out[54]: array([  0, 100, 100, 100,   4, 100, 100, 100,   8, 100, 100, 100])
2 of 3
2

numpy.delete :

In [18]: arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [19]: arr = np.delete(arr, np.arange(0, arr.size, 4))

In [20]: arr
Out[20]: array([1, 2, 3, 5, 6, 7, 9])
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-multiply-k-to-every-nth-element
Python - Multiply K to every Nth element - GeeksforGeeks
May 16, 2023 - Convert the modified numpy array back to a list. Print the original list after updating the Nth element. ... #Python3 code to demonstrate #Multiply K to every Nth element #using numpy array import numpy as np #initializing list test_list = [1, 4, 5, 6, 7, 8, 9, 12] #printing the original list print ("The original list is : " + str(test_list)) #initializing N N = 3 #initializing K K = 2 #converting list to numpy array np_array = np.array(test_list) #multiplying every Nth element by K using numpy indexing np_array[::N] = np_array[::N] * K #converting numpy array back to list test_list = np_array.tolist() #printing result print ("The list after multiplying K to every Nth element : " + str(test_list))
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-skip-every-nth-index-of-numpy-array
How to Skip every Nth index of Numpy array?
Original array: [ 10 20 30 40 50 ... provides a simpler way to access every Nth element directly using the step parameter in slice notation [start:stop:step]....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ when wanting to select every nth element while iterating through an array, is it more 'pythonic' to use slice notation or the modulo operator?
r/learnpython on Reddit: When wanting to select every Nth element while iterating through an array, is it more 'pythonic' to use slice notation or the modulo operator?
March 9, 2021 -

For example, if I want to iterate through an array and select only every 20th element, is it considered more 'pythonic' to do it like this...

for x in range(100)[::20]:
    pass

...or this...

for x in range(100):
    if x % 20 == 0:
        pass

I read through PEP 204 (rejected) but it only covered list ranges and slice notation for stepping, not modulo operators.

Thanks!

๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ subsampling-every-nth-entry-in-a-numpy-array.aspx
Python - Subsampling every nth entry in a NumPy array
There is a common approach of slicing and repeating the elements after some steps. Start:Stop:Step fashion allows us to solve this problem. ... # Import numpy import numpy as np # Creating a numpy array arr = np.array( [1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20] ) # Display original array print("Original array:\n",arr,"\n") # Slicing every 5th element and starting # from 1st element res = arr[0::5] # Display result print("Subsampled array:\n",res,"\n")
๐ŸŒ
ProjectPro
projectpro.io โ€บ recipes โ€บ select-elements-from-numpy-array-in-python
How to Select Columns in NumPy Array using np.select? -
February 22, 2024 - ... The expression arr[:, 1:3] ... the column indices in the slice as needed. You can use array slicing with a step size to select every nth element in a NumPy array....
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.2 โ€บ reference โ€บ generated โ€บ numpy.take.html
numpy.take โ€” NumPy v2.2 Manual
When axis is not None, this function ... if you need elements along a given axis. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...]. Explained without fancy indexing, this is equivalent to the following use of ndindex, which sets each of ii, jj, ...
๐ŸŒ
Moonbooks
en.moonbooks.org โ€บ Articles โ€บ How-to-get-every-nth-element-in-a-list-in-python-
How to get every nth element in a list in python ? - Moonbooks
August 7, 2021 - To get every nth element in list, between indexes m1,m2, a solution is to do mylist[m1:m2:n]. Example: