Subsampling Every Nth Entry in a Numpy Array

Python/Numpy Slicing an array every nth row

You are probably looking for np.split()

Computationally fastest way to make a new numpy array of every n elements from a numpy array

The absolute fastest way to do this is to write an extension module in pure C and use the buffer protocol to access the data directly. If you use Cython or another such tool to write the C for you, you may see small amounts of performance lost in automatic reference counting. Since you still have to do manual reference counting in handwritten C, the difference is likely to be negligible to nonexistent.

This will have marginally less overhead than the slicing syntax NumPy provides out of the box. However, assuming you use NumPy correctly, the overall performance gain is likely to be small and constant, so it's not clear to me that this is worth the extra effort in any reasonable situation.

Averaging over every n elements of a numpy array

If your array arr has a length divisible by 3:

np.mean(arr.reshape(-1, 3), axis=1)

Reshaping to a higher dimensional array and then performing some form of reduce operation on one of the additional dimensions is a staple of numpy programming.

How to change element in np.array by index

There you go:

import numpy as np
arr = np.array([1,2,3,4])
for i in range(len(arr)):
if i%2==0:
arr[i]=10
print(arr)

Output:

[10  2 10  4]

Without Loop and if Statements:

import numpy as np
arr = np.array([1,2,3,4])
arr[0::2] = 10

Output:

array([10,  2, 10,  4])

I've used Numpy's Slicing which works as [start:stop:step]



Related Topics



Leave a reply



Submit