Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you rotate the numbers in an numpy array of shape (n,) or (n,1)?

Tags:

python

numpy

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)
like image 882
atomh33ls Avatar asked Apr 12 '13 11:04

atomh33ls


People also ask

What is the meaning of reshape (- 1 1?

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.

How do you reshape an array in one direction in Python?

Flattening array means converting a multidimensional array into a 1D array. We can use reshape(-1) to do this.

What is a 1 dimensional NumPy array?

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.


1 Answers

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.

like image 101
Francesco Montesano Avatar answered Sep 19 '22 12:09

Francesco Montesano