【问题标题】:append 2d time series array in python [closed]在python中附加二维时间序列数组[关闭]
【发布时间】:2017-12-21 20:36:58
【问题描述】:

我在不同的 10 个 NETCDF 文件中有年度时间序列数据。文件形状为:

value.shape = 

(365, 310, 250)

我尝试制作一个形状如下的数组:

(3650, 310,250)

通过将年度数据附加到其中。我使用了这个功能但没有用:

files = glob.glob('/home/user/data/*.nc')    
time_series = np.array([[]])
    for i in files:
        yearly = Dataset(i,'r')
        value = yearly.variables['AOD'][:,:,:]
        time_series = np.append(time_series,value)

任何帮助都将受到高度评价。

【问题讨论】:

  • 没用 - 那么会发生什么呢?
  • 我得到了这个形状:time_series.shape = (442912500,)
  • numpy.append "如果未指定axis,则值可以是任意形状在使用前会被展平。"
  • 在执行时:time_series = np.append(time_series,value,axis = 0),我收到此错误:所有输入数组必须具有相同的维数

标签: python arrays numpy netcdf


【解决方案1】:

我将如何更改您的代码:

def make_array(loc, shape = (365, 31, 25)):  
    # loc is string, can have any number of files, can change shape of data
    files = glob.glob(str(loc) + '/*.nc')    
    time_series = np.empty((len(files),) + shape) # create an extra dimension for files, 'np.empty' doesn't waste time initializing
    for i, j in enumerate(files): # enumerate gives you indices
        yearly = Dataset(j, 'r')
        time_series[i] = yearly.variables['AOD'][:, :, :]
    return time_series.reshape(*((-1,) + shape[1:])) # -1 allows size to change

【讨论】:

  • numpy 的主要优势之一是它能够跟踪多个维度。构建具有更多维度的数组然后重新整形/索引/掩码/跨步到您需要的几乎总是更容易和更清晰。尝试直接跳转到后续函数所需的数据格式几乎总是premature optimization 的情况。
【解决方案2】:

如果你一开始就知道合并数组的大小,那么创建一个正确大小的 Numpy 数组就容易多了。例如(我把尺寸缩小了一点..):

import numpy as np

merged_values = np.empty((3650, 31, 25))

for i in range(10):
    value = np.random.random((365, 31, 25))
    merged_values[i*365:(i+1)*365] = value

【讨论】:

  • 作为旁注;就性能而言,它因问题而异,但根据我的经验,从正确大小的数组开始并填充通常比使用 np.appendlist.append 快得多
  • 构建一个(n, 365, 31, 25)数组然后做reshape(-1,31,25)更清晰和可扩展。
  • 这确实是一个优雅的解决方案(我试过了),但我不确定reshape(-1,...) 如何/为什么工作?
  • reshape(-1, . . .)means 计算该维度相对于原始大小除以其他维度大小的乘积的大小。在这种情况下,它将是 442912500/(25*31) = 3650 = 365*10,但如果你有更多或更少的文件,它会有所不同。
  • @DanielF reshape (-1,310,250) 也适用于我。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2021-09-28
  • 2016-05-29
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多