Skip to content
Advertisement

Skip every nth index of numpy array

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:

JavaScript

If n = 4 then the result would be

JavaScript

Note: the numpy requirement is due to this being used for a machine learning assignment where the dependencies are fixed.

Advertisement

Answer

Approach #1 with modulus

JavaScript

Sample run –

JavaScript

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 –

JavaScript

Here’s the memory requirement stat –

JavaScript

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

JavaScript

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 –

JavaScript

Sample run –

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement