numpy数组中不需要的额外维度

bjd*_*385 14 python numpy pyfits

我打开了一个.fits图片:

scaled_flat1 = pyfits.open('scaled_flat1.fit')

scaled_flat1a = scaled_flat1[0].data
Run Code Online (Sandbox Code Playgroud)

当我打印它的形状时:

print scaled_flat1a.shape
Run Code Online (Sandbox Code Playgroud)

我得到以下内容:

(1, 1, 510, 765)
Run Code Online (Sandbox Code Playgroud)

我希望它阅读:

(510,765)
Run Code Online (Sandbox Code Playgroud)

我怎么摆脱之前的两个呢?

ask*_*han 32

有一个方法叫做squeeze你想要的方法:

从数组的形状中删除一维条目.

参数

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.
Run Code Online (Sandbox Code Playgroud)

返回

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`.
Run Code Online (Sandbox Code Playgroud)

例如:

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)
Run Code Online (Sandbox Code Playgroud)


Rog*_*Fan 5

我假设scaled_flat1a是一个numpy数组?在这种情况下,它应该像reshape命令一样简单。

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)
Run Code Online (Sandbox Code Playgroud)