ShanZhengYang February 2016

How to reshape this numpy array to exclude the "extra dimension"?

I have a numpy array arr1 which it an output of a function. The array has an "extra" dimension caused by each element inside the numpy array being cast as a numpy array itself.

arr1.shape outputs (100, 20, 1)

If I print the array, print(arr1[0]) outputs

array([[-212537.61715316],
       [   7258.38476409],
       [  37051.91250884],
       [-146278.00512207],
       [-185792.24620168],
       [-200794.59538468],
       [-195981.27879612],
       [-177912.26034464],
       [-152212.805867  ],
       [-118873.26452198],
       [ -64657.64682999],
       [ 306884.11196766],
       [-191073.9891907 ],
       [-104992.44840277],
       [ -67834.43041102],
       [ -21810.77063542],
       [  17307.24511071],
       [  55607.49775471],
       [  91259.82533592],
       [ 119207.40589797]])

If I reshape with arr1.reshape((100,20)), I get the following output for print(arr1.reshape((100,20))[0]):

array([-212537.61715316,    7258.38476409,   37051.91250884,
       -146278.00512207, -185792.24620168, -200794.59538468,
       -195981.27879612, -177912.26034464, -152212.805867  ,
       -118873.26452198,  -64657.64682999,  306884.11196766,
       -191073.9891907 , -104992.44840277,  -67834.43041102,
        -21810.77063542,   17307.24511071,   55607.49775471,
         91259.82533592,  119207.40589797])

My question is: how do I exclude this "extra" one, but retain the original shape of the array arr1?

Is the best method to use .reshape()? If not, what is the best way to do this?

Answers


daveydave400 February 2016

You might be looking for numpy.squeeze:

http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.squeeze.html

a = np.arange(10*20).reshape((10, 20, 1))
print(a.shape)
# (10, 20, 1)
a = a.squeeze()
print(a.shape)
# (10, 20)

Note the other answer since your reshape should have worked you were just looking at the output incorrectly.


hpaulj February 2016

You are using reshape correctly.

 arr2 = arr1.reshape((100,20))

The shape of this will be (100,20), the same as arr1 without the last dimension.

arr1[0] has shape (20,1), and thus prints as a column.

arr2[0] has shape (20,), and thus prints as a row(s) (count the brackets). You might not like the display, but the shape is correct.

squeeze can also be used to take out the extra dimension, but the results will be same.

print(arr2[0][:,None]) should print as a column. It effectively adds that extra dimension back on prior to printing.

Post Status

Asked in February 2016
Viewed 2,918 times
Voted 8
Answered 2 times

Search




Leave an answer