Say I have a numpy array:
>>> a
array([0,1,2,3,4])
and I want to "rotate" it to get:
>>> b
array([4,0,1,2,3])
What is the best way?
I have been converting to a deque and back (see below) but is there a better way?
b = deque(a)
b.rotate(1)
b = np.array(b)
In NumPy, -1 in reshape(-1) refers to an unknown dimension that the reshape() function calculates for you. It is like saying: “I will leave this dimension for the reshape() function to determine”. A common use case is to flatten a nested array of an unknown number of elements to a 1D array.
Flattening array means converting a multidimensional array into a 1D array. We can use reshape(-1) to do this.
One dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple.
Just use the numpy.roll
function:
a = np.array([0,1,2,3,4])
b = np.roll(a,1)
print(b)
>>> [4 0 1 2 3]
See also this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With