将时间序列数据从csv转换为netCDF python

时间:2019-05-24 12:56:48

标签: python pandas csv netcdf netcdf4

此过程中的主要问题是以下代码:

precip[:] = orig

产生以下错误:

ValueError: cannot reshape array of size 5732784 into shape (39811,144,144)

我有两个CSV文件,其中一个CSV文件包含变量(降水)的所有实际数据,每列都作为一个桩号,它们的相应坐标位于第二个单独的CSV文件中。 我的样本数据在google drive here中。

如果要查看数据本身,但是我的第一个CSV文件的形状为(39811,144),而第二个CSV文件的形状为(171,10),但请注意;我只将切片的数据帧用作(144,2)。

这是代码:

stations = pd.read_csv(stn_precip)
stncoords = stations.iloc[:,[0,1]][:144]
orig = pd.read_csv(orig_precip, skiprows = 1, names = stations['Code'][:144])

lons = stncoords['X']
lats = stncoords['Y']

ncout = netCDF4.Dataset('Precip_1910-2018_homomod.nc', 'w')

ncout.createDimension('longitude',lons.shape[0])
ncout.createDimension('latitude',lats.shape[0])
ncout.createDimension('precip',orig.shape[1])
ncout.createDimension('time',orig.shape[0])

lons_out = lons.tolist()
lats_out = lats.tolist()
time_out = orig.index.tolist()

lats = ncout.createVariable('latitude',np.dtype('float32').char,('latitude',))
lons = ncout.createVariable('longitude',np.dtype('float32').char,('longitude',))
time = ncout.createVariable('time',np.dtype('float32').char,('time',))
precip = ncout.createVariable('precip',np.dtype('float32').char,('time', 'longitude','latitude'))

lats[:] = lats_out
lons[:] = lons_out
time[:] = time_out
precip[:] = orig
ncout.close()

我主要将我的代码基于这篇文章:convert-csv-to-netcdf 但不包含变量“ TIME”作为第三维,所以这就是我失败的地方。 我想我应该期望降水变量具有以下形式的形状:(39811,144,144),但是该错误表明并非如此。

不确定如何处理,感谢您的投入。

1 个答案:

答案 0 :(得分:1)

由于您有来自不同站点的数据,因此建议您为netCDF文件使用维度station,而不要分开lonlat。当然,您可以将每个测站的经度和纬度保存为单独的变量。

这里是一种可能的解决方案,以您的代码为例:

#!/usr/bin/env ipython
import pandas as pd
import numpy as np
import netCDF4

stn_precip='Precip_1910-2018_stations.csv'
orig_precip='Precip_1910-2018_origvals.csv'
stations = pd.read_csv(stn_precip)
stncoords = stations.iloc[:,[0,1]][:144]
orig = pd.read_csv(orig_precip, skiprows = 1, names = stations['Code'][:144])

lons = stncoords['X']
lats = stncoords['Y']
nstations = np.size(lons)

ncout = netCDF4.Dataset('Precip_1910-2018_homomod.nc', 'w')

ncout.createDimension('station',nstations)
ncout.createDimension('time',orig.shape[0])

lons_out = lons.tolist()
lats_out = lats.tolist()
time_out = orig.index.tolist()

lats = ncout.createVariable('latitude',np.dtype('float32').char,('station',))
lons = ncout.createVariable('longitude',np.dtype('float32').char,('station',))
time = ncout.createVariable('time',np.dtype('float32').char,('time',))
precip = ncout.createVariable('precip',np.dtype('float32').char,('time', 'station'))

lats[:] = lats_out
lons[:] = lons_out
time[:] = time_out
precip[:] = orig
ncout.close()

因此有关输出文件(ncdump -h Precip_1910-2018_homomod.nc)的信息如下: enter image description here

相关问题