简体   繁体   English

使用numpy.reshape()添加尺寸

[英]Adding dimensions using numpy.reshape()

I have a situation I'm trying to resolve. 我有一种情况要解决。 I have climate model data in an array with 480 monthly entries at the latitude and longitude grid points of this model (the particulars are irrelevant). 我在该模型的纬度和经度网格点上以阵列形式包含了480个每月输入的气候模型数据(具体情况无关紧要)。 That is, I have a numpy array with dimensions (480, lat, lon). 也就是说,我有一个尺寸为(480,纬度,经度)的numpy数组。

I need to create yearly averages at each spatial grid point. 我需要在每个空间网格点上创建年度平均值。 The way I would like to do this is by using numpy.reshape() to make a 4D array with dimensions (480/12, 12, lat, lon) (where I group the timesteps into groups of 12 and restack them, as it were). 这样做的方法是通过使用numpy.reshape()以与尺寸(十二分之四百八十零,12,LAT,LON)(其中,I组四维阵列中的时间步长为12的基团和它们重新堆叠,因为它人)。 Then I would average along the second axis ( np.mean(dat_new, axis = 1) ). 然后,我将沿第二个轴np.mean(dat_new, axis = 1)平均( np.mean(dat_new, axis = 1) )。

The whole thing would be 整个事情将会是

dat_new = np.reshape(dat, (dat.shape[0]/12, 12, dat.shape[1], dat.shape[2]))
dat_annual_mean = np.mean(dat_new, axis = 1)

My question is: does reshape work this way? 我的问题是:重塑是否可以这种方式工作? Would it rearrange things in the correct order? 会以正确的顺序重新安排事情吗? If not (or even if so) is there another (potentially less clumsy way to do this?) 如果不是(或者即使是这样),还有另一种(可能不太笨拙的方法吗?)

Thanks. 谢谢。

You should first permute the dimensions so that your data is reshaped in the correct order. 您应该首先对尺寸进行置换,以便以正确的顺序重塑数据。

dat_new=np.reshape(np.transpose(dat,(1,2,0)),
                   (dat.shape[1],dat.shape[2],dat.shape[0]//12, 12))
dat_annual_mean = np.mean(dat_new, axis = 3)

ie it will give you an array with dimensions (lat, lon, 480/12), which you can transpose further if necessary. 即,它将为您提供一个尺寸为(lat,lon,480/12)的数组,您可以在必要时进一步转置。

Simplified so we can see the whole array, this is what I think you are trying to do: 简化,以便我们可以看到整个数组,这是我认为您正在尝试做的事情:

In [608]: arr = np.zeros((3*4,2),int)
In [609]: arr[:,0]=np.arange(12)
In [610]: arr
Out[610]: 
array([[ 0,  0],
       [ 1,  0],
       [ 2,  0],
       [ 3,  0],
       [ 4,  0],
       [ 5,  0],
       [ 6,  0],
       [ 7,  0],
       [ 8,  0],
       [ 9,  0],
       [10,  0],
       [11,  0]])
In [611]: arr.reshape(3,4,2)
Out[611]: 
array([[[ 0,  0],
        [ 1,  0],
        [ 2,  0],
        [ 3,  0]],

       [[ 4,  0],
        [ 5,  0],
        [ 6,  0],
        [ 7,  0]],

       [[ 8,  0],
        [ 9,  0],
        [10,  0],
        [11,  0]]])
In [612]: _.mean(axis=1)
Out[612]: 
array([[ 1.5,  0. ],
       [ 5.5,  0. ],
       [ 9.5,  0. ]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM