Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the best way to add an extra dimension to a numpy array in one line of code?

If k is an numpy array of an arbitrary shape, so k.shape = (s1, s2, s3, ..., sn), and I want to reshape it so that k.shape becomes (s1, s2, ..., sn, 1), is this the best way to do it in one line?

k.reshape(*(list(k.shape) + [1]) 
like image 575
qAp Avatar asked Jul 24 '13 13:07

qAp


People also ask

How do I add an extra dimension to a NumPy array?

You can add new dimensions to a NumPy array ndarray (= unsqueeze a NumPy array) with np. newaxis , np. expand_dims() and np. reshape() (or reshape() method of ndarray ).

How do you increase dimensions in Python?

With the help of Numpy. expand_dims() method, we can get the expanded dimensions of an array by using Numpy. expand_dims() method. Return : Return the expanded array.

Can NumPy arrays have more than 2 dimensions?

Creating arrays with more than one dimensionIn general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.

How do I change the size of an array in NumPy?

The shape of the array can also be changed using the resize() method. If the specified dimension is larger than the actual array, The extra spaces in the new array will be filled with repeated copies of the original array.


1 Answers

It's easier like this:

k.reshape(k.shape + (1,)) 

But if all you want is to add an empty dimension at the end, you should use numpy.newaxis:

import numpy as np k = k[..., np.newaxis] 

or

k = k[..., None] 

(See the documentation on slicing).

like image 190
tiago Avatar answered Sep 23 '22 04:09

tiago