我有月度数据,但将数据上升到特定月份,然后是该月的所有年份,我如何 return 按时间顺序排列的数据集?

I have monthly data but up the data into specific month and then all the years of that month, how do I return a chronologically ordered dataset?

我有一个 4d 数据集,其中第一个轴在技术上是月份,第二个轴是那个月的所有年份,然后是空间坐标。 所以 1 月 (0) 有 27 个值代表 27 年的 1 月。

我的目标是重建时间序列,使其成为第 1 年的 1 月、第 1 年的 2 月...第 2 年的 1 月、第 2 年的 2 月等。这只是一个正常的每月时间序列。然而,我对数据集重新排序的函数是错误的,并且没有将正确的月份和年份一起排序。

有人能看出我的功能有什么问题吗?我的新“合并月份”数组的形状是正确的,但它没有正确地重新排序数组“数据”:

# 4d data set, with 12 month, 27 years (so each month [jan - dec] has 27 points):
data = np.random.rand(12,27,281,375)


#function to try and get data back into chronological order (1st month - year 1, 2nd month - year 1...)
def merge_months(split_data):
    merged_months = []
    for month in range(split_data.shape[0]):
        for year in range(split_data.shape[1]): 
            print(month, year)
            merged_months.append(split_data[month][year])
    return merged_months

merged_months = np.array(merge_months(data))

print(merged_months.shape)
(324,281,374)

我期望重新排序的输出是一个数组:

(第 1 年的第一个值,第 2 个值是第 1 年的 2 月,....第 13 个值是第 2 年的 1 月,第 14 个值是第 2 年的 2 月...等)。

有人好心建议:

num_years = 27
num_months = 12
height = 281
width = 375

data = np.random.rand(num_months, num_years, height, width)

# The reshape is equivalent to .reshape(num_years * num_months, height, width)
data_ord = np.swapaxes(data, 0, 1).reshape(-1, *data.shape[-2:])

# Check for february, year 5, pixel (34, 34)
month_idx = 1  # february
year_idx = 4  # year 5
height_idx = 34
width_idx = 34

feb5px1 = data[month_idx, year_idx, height_idx, width_idx]
feb5px2 = data_ord[year_idx * num_months + month_idx, height_idx, width_idx]

但我想将它应用于所有网格点,而不仅仅是一个....

我试过了:

test = []
num_months = 12

for yr_idx in range(27):
    for month_idx in range(12):
        test.apppend(d[year_idx*num_months+month_idx, :,:])
        

但我收到一条错误消息:'list' 对象没有属性 'apppend'

我认为你只需要交换前两个轴,然后通过整形将它们压平,请参见下面的代码:

num_years = 27
num_months = 12
height = 281
width = 375

data = np.random.rand(num_months, num_years, height, width)

# The reshape is equivalent to .reshape(num_years * num_months, height, width)
data_ord = np.swapaxes(data, 0, 1).reshape(-1, *data.shape[-2:])

# Check for february, year 5, pixel (34, 34)
month_idx = 1  # february
year_idx = 4  # year 5
height_idx = 34
width_idx = 34

feb5px1 = data[month_idx, year_idx, height_idx, width_idx]
feb5px2 = data_ord[year_idx * num_months + month_idx, height_idx, width_idx]

assert feb5px1 == feb5px2

# And for all pixels this month
feb5_1 = data[month_idx, year_idx]
feb5_2 = data_ord[year_idx * num_months + month_idx]

assert np.allclose(feb5_1, feb5_2)