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
Stopping a Thread After a Certain Amount of Time
Target Wsgi Script Cannot Be Loaded as Python Module
Finding the Consecutive Zeros in a Numpy Array
Generating File to Download with Django
Deleting Multiple Columns Based on Column Names in Pandas
Is It Pythonic to Import Inside Functions
Python Argparse - Add Argument to Multiple Subparsers
Most Pythonic Way to Interleave Two Strings
No Module Named 'Pandas._Libs.Tslibs.Timedeltas' in Pyinstaller
Pythonic Way to Create Union of All Values Contained in Multiple Lists
Longest Common Substring from More Than Two Strings
Opencv Python Rotate Image by X Degrees Around Specific Point
How to Force a List to a Fixed Size
Calling Dot Products and Linear Algebra Operations in Cython
Remove a Tag Using Beautifulsoup But Keep Its Contents