Skip to content

Reshaping a numpy array

An answer to this question on Stack Overflow.

Question

I have the following NumPy array,

[[date1,num1],[date2,num2],[date3,num3],[date4,num4]]

I want to divide it as follows:

[ [ [date1,num1],[date2,num2] ] , [ [date3,num3],[date4,num4] ] ]

Can anyone suggest something?

Answer

You can use Numpy's reshape method and the -1 argument to reshape arrays of arbitrary length between the two forms you specify. Like so:

import numpy as np
#Generate an array of the form you specify of arbitrary length
arraylen = 10
a        = np.array([ ['date'+str(i),'num'+str(i)] for i in range(arraylen*2)])
#Reshape the array per your specifications
a.reshape((-1,2,2))

Gives

array([[['date0', 'num0'],
        ['date1', 'num1']],
       [['date2', 'num2'],
        ['date3', 'num3']],
        ...