Most efficient way to reverse a numpy array
reversed_arr = arr[::-1]
gives a reversed view into the original array arr
. Any changes made to the original array arr
will also be immediately visible in reversed_arr
. The underlying data buffers for arr
and reversed_arr
are shared, so creating this view is always instantaneous, and does not require any additional memory allocation or copying for the array contents.See also, this discussion on NumPy views: How do I create a view onto a NumPy array?
Possible solutions to performance problems regarding views
Are you re-creating the view more often than you need to? You should be able to do something like this:arr = np.array(some_sequence)
reversed_arr = arr[::-1]
do_something(arr)
look_at(reversed_arr)
do_something_else(arr)
look_at(reversed_arr)
I'm not a numpy expert, but this seems like it would be the fastest way to do things in numpy. If this is what you are already doing, I don't think you can improve on it. Efficiently sorting a numpy array in descending order?
temp[::-1].sort()
sorts the array in place, whereas np.sort(temp)[::-1]
creates a new array.
In [25]: temp = np.random.randint(1,10, 10)
In [26]: temp
Out[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])
In [27]: id(temp)
Out[27]: 139962713524944
In [28]: temp[::-1].sort()
In [29]: temp
Out[29]: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])
In [30]: id(temp)
Out[30]: 139962713524944
Most efficient ways to compare arrays in numpy?
From the answer: Finding the (x,y) indexes of specific (R,G,B) color values from images stored in NumPy ndarrays
The solution to your problem would be:
cords = list(zip(*np.where(np.all(np_pixels == torso, axis=-1))))
Writing an efficient code for applying a reverse operation using masks in NumPy
You can use boolean indexing:
b = np.zeros_like(m, dtype=float) # change dtype to `int` if that's what you want.
b[m] = c
Outputarray([1., 2., 3., 4., 0., 0., 7., 8., 9.])
What is the most efficient way of finding the ranks of one numpy array in another?
Use searchsorted
ind = np.argsort(y)
np.searchsorted(y, x, sorter=ind)
# array([1, 3, 2, 1, 0], dtype=int64)
If y
has duplicates, you may have to tinker with the side
argument.
Related Topics
Apt Command Line Interface-Like Yes/No Input
Difference Between Exit(0) and Exit(1) in Python
Differencebetween Np.Array() and Np.Asarray()
Can't Use '\1' Backreference to Capture-Group in a Function Call in Re.Sub() Repr Expression
Representing and Solving a Maze Given an Image
Adding a Y-Axis Label to Secondary Y-Axis in Matplotlib
What Is the Purpose of Meshgrid in Python/Numpy
Define CSS Class in Django Forms
Building a Minimal Plugin Architecture in Python
How to Limit the Maximum Value of a Numeric Field in a Django Model
Python - Legend Overlaps with the Pie Chart
Python Pip on Windows - Command 'Cl.Exe' Failed
Broken References in Virtualenvs
How to Log a Python Error with Debug Information