Convert numpy array (n, m) to array (n, m, 1,1) in form

My starting point is a pandas dataframe which I am converting to a numpy array:

> df = pd.DataFrame({"a":[1,2,3,4],"b":[4,5,6,7],"c":[7,8,9,10]})
> arr = df.as_matrix()

      

Now the array is 2-dimensional in shape (4,3):

> arr
array([[ 1,  4,  7],
       [ 2,  5,  8],
       [ 3,  6,  9],
       [ 4,  7, 10]])

      

What I would like to do is convert arr

to its 4-dimensional and (4,3,1,1) shape equivalent, effectively mapping each distinct element like fx 5

to [[5]]

.

The new one arr

will be:

array([[ [[1]],  [[4]],  [[7]]  ],
       [ [[2]],  [[5]],  [[8]]  ],
       [ [[3]],  [[6]],  [[9]]  ],
       [ [[4]],  [[7]],  [[10]] ]])

      

How can I do this elegantly and quickly?

+3


source to share


1 answer


Do arr[:, :, None, None]

to add two additional axes. Here's an example:

In [5]: arr[:, :, None, None].shape
Out[5]: (4, 3, 1, 1)

      

None

in indexing is a synonym np.newaxis

that selects data and adds a new axis. Many people would rather write above like



arr[:, :, np.newaxis, np.newaxis]

for readability reasons

+4


source







All Articles