NumPy数组中的多余维度

18 投票
2 回答
25242 浏览
提问于 2025-04-18 18:13

我打开了一个 .fits 格式的图像:

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

然后我打印它的形状:

print scaled_flat1a.shape

我得到了以下结果:

(1, 1, 510, 765)

我希望它显示成:

(510, 765)

我该怎么去掉前面的两个1呢?

2 个回答

6

我假设 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)
37

有一个叫做 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.

返回值

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`.

比如说:

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)

撰写回答