Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwanted extra dimensions in NumPy array

I've opened a .fits image:

scaled_flat1 = pyfits.open('scaled_flat1.fit')   
scaled_flat1a = scaled_flat1[0].data

and when I print its shape:

print scaled_flat1a.shape

I get the following:

(1, 1, 510, 765)

I want it to read:

(510, 765)

How do I get rid of the two ones before it?

like image 221
bjd2385 Avatar asked Aug 22 '14 18:08

bjd2385


People also ask

How do I drop a dimension in NumPy?

You can use numpy. squeeze() to remove all dimensions of size 1 from the NumPy array ndarray . squeeze() is also provided as a method of ndarray .

Can NumPy arrays have more than 2 dimensions?

numpy arrays can have 0, 1, 2 or more dimensions. C. shape returns a tuple of the dimensions; it may be of 0 length, () , 1 value, (81,) , or 2 (81,1) .

What does .all do in NumPy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.


2 Answers

There is the method called squeeze which does just what you want:

Remove single-dimensional entries from the shape of an array.

Parameters

a : array_like
    Input data.
axis : None or int or tuple of ints, optional
    .. versionadded:: 1.7.0

    Selects a subset of the single-dimensional entries in the
    shape. If an axis is selected with shape entry greater than
    one, an error is raised.

Returns

squeezed : ndarray
    The input array, but with with all or a subset of the
    dimensions of length 1 removed. This is always `a` itself
    or a view into `a`.

for example:

import numpy as np

extra_dims = np.random.randint(0, 10, (1, 1, 5, 7))
minimal_dims = extra_dims.squeeze()

print minimal_dims.shape
# (5, 7)
like image 131
askewchan Avatar answered Oct 17 '22 20:10

askewchan


I'm assuming scaled_flat1a is a numpy array? In that case, it should be as simple as a reshape command.

import numpy as np

a = np.array([[[[1, 2, 3],
                [4, 6, 7]]]])
print(a.shape)
# (1, 1, 2, 3)

a = a.reshape(a.shape[2:])  # You can also use np.reshape()
print(a.shape)
# (2, 3)
like image 39
Roger Fan Avatar answered Oct 17 '22 21:10

Roger Fan