将CSV转换为NetCDF
我正在尝试通过Python将一个.csv文件转换为netCDF4格式,但我在如何将.csv表格中的信息存储到netCDF中遇到了困难。我最关心的是如何将列中的变量声明为可用的netCDF4格式?我找到的资料大多是从netCDF4提取信息到.csv或ASCII格式。我提供了示例数据、示例代码和我在声明适当数组时遇到的错误。任何帮助都将不胜感激。
下面是示例表格:
Station Name Country Code Lat Lon mn.yr temp1 temp2 temp3 hpa
Somewhere US 12340 35.52 23.358 1.19 -8.3 -13.1 -5 69.5
Somewhere US 12340 2.1971 -10.7 -13.9 -7.9 27.9
Somewhere US 12340 3.1971 -8.4 -13 -4.3 90.8
我的示例代码是:
#!/usr/bin/env python
import scipy
import numpy
import netCDF4
import csv
from numpy import arange, dtype
#声明空数组
v1 = []
v2 = []
v3 = []
v4 = []
#打开csv文件,并为每个标题声明数组变量
f = open('station_data.csv', 'r').readlines()
for line in f[1:]:
fields = line.split(',')
v1.append(fields[0]) #station
v2.append(fields[1])#country
v3.append(int(fields[2]))#code
v4.append(float(fields[3]))#lat
v5.append(float(fields[3]))#lon
#more variables included but this is just an abridged list
print v1
print v2
print v3
print v4
#转换为netcdf4框架,使其作为netcdf工作
ncout = netCDF4.Dataset('station_data.nc','w')
# 纬度和经度。缺失的数字用NaN表示
lats_out = -25.0 + 5.0*arange(v4,dtype='float32')
lons_out = -125.0 + 5.0*arange(v5,dtype='float32')
# 输出数据。
press_out = 900. + arange(v4*v5,dtype='float32') # 1d array
press_out.shape = (v4,v5) # reshape to 2d array
temp_out = 9. + 0.25*arange(v4*v5,dtype='float32') # 1d array
temp_out.shape = (v4,v5) # reshape to 2d array
# 创建纬度和经度的维度。
ncout.createDimension('latitude',v4)
ncout.createDimension('longitude',v5)
# 定义坐标变量。它们将保存坐标信息
lats = ncout.createVariable('latitude',dtype('float32').char,('latitude',))
lons = ncout.createVariable('longitude',dtype('float32').char,('longitude',))
# 为坐标变量的数据分配单位属性。这会将一个文本属性附加到每个坐标变量上,包含单位信息。
lats.units = 'degrees_north'
lons.units = 'degrees_east'
# 将数据写入坐标变量。
lats[:] = lats_out
lons[:] = lons_out
# 创建压力和温度变量
press = ncout.createVariable('pressure',dtype('float32').char,('latitude','longitude'))
temp = ncout.createVariable('temperature',dtype('float32').char,'latitude','longitude'))
# 设置单位属性。
press.units = 'hPa'
temp.units = 'celsius'
# 将数据写入变量。
press[:] = press_out
temp[:] = temp_out
ncout.close()
f.close()
错误:
Traceback (most recent call last):
File "station_data.py", line 33, in <module>
v4.append(float(fields[3]))#lat
ValueError: could not convert string to float:
3 个回答
虽然上面提到的 xarray
是一个很棒的工具,但也值得看看英国气象局的 iris
库。Iris 的一个主要优点是它能帮助创建符合气候预测(CF 规范)的 netCDF 文件。它通过提供一些辅助功能来定义 标准名称、单位、坐标系统和其他元数据规范,从而实现这一点。此外,它还提供绘图、子集提取和分析的工具。
对于像这样的地球科学数据,CF 是 netCDF 文件的推荐标准。
作为使用的一个例子,这个 Python 笔记本 重新实现了上面的 AO/NAO 示例。
这项工作非常适合使用xarray,这是一个Python库,它有一个数据集对象,可以表示netcdf常见数据模型。下面是一个你可以尝试的例子:
import pandas as pd
import xarray as xr
url = 'http://www.cpc.ncep.noaa.gov/products/precip/CWlink/'
ao_file = url + 'daily_ao_index/monthly.ao.index.b50.current.ascii'
nao_file = url + 'pna/norm.nao.monthly.b5001.current.ascii'
kw = dict(sep='\s*', parse_dates={'dates': [0, 1]},
header=None, index_col=0, squeeze=True, engine='python')
# read into Pandas Series
s1 = pd.read_csv(ao_file, **kw)
s2 = pd.read_csv(nao_file, **kw)
s1.name='AO'
s2.name='NAO'
# concatenate two Pandas Series into a Pandas DataFrame
df=pd.concat([s1, s2], axis=1)
# create xarray Dataset from Pandas DataFrame
xds = xr.Dataset.from_dataframe(df)
# add variable attribute metadata
xds['AO'].attrs={'units':'1', 'long_name':'Arctic Oscillation'}
xds['NAO'].attrs={'units':'1', 'long_name':'North Atlantic Oscillation'}
# add global attribute metadata
xds.attrs={'Conventions':'CF-1.0', 'title':'AO and NAO', 'summary':'Arctic and North Atlantic Oscillation Indices'}
# save to netCDF
xds.to_netcdf('/usgs/data2/notebook/data/ao_and_nao.nc')
然后运行 ncdump -h ao_and_nao.nc
会产生:
netcdf ao_and_nao {
dimensions:
dates = 782 ;
variables:
double dates(dates) ;
dates:units = "days since 1950-01-06 00:00:00" ;
dates:calendar = "proleptic_gregorian" ;
double NAO(dates) ;
NAO:units = "1" ;
NAO:long_name = "North Atlantic Oscillation" ;
double AO(dates) ;
AO:units = "1" ;
AO:long_name = "Arctic Oscillation" ;
// global attributes:
:title = "AO and NAO" ;
:summary = "Arctic and North Atlantic Oscillation Indices" ;
:Conventions = "CF-1.0" ;
请注意,你可以通过 pip
安装 xarray
,但如果你使用的是Anaconda Python发行版,可以通过以下方式从Anaconda.org/conda-forge频道安装:
conda install -c conda-forge xarray
如果你查看你的输入文件,你会发现第二行的Lat列没有对应的值。当你读取这个csv文件时,这个值,也就是fields[3]
,会被存储为空字符串""
。这就是你遇到ValueError
的原因。
你可以不使用默认的函数,而是定义一个新的函数来处理这个错误:
def str_to_float(str):
try:
number = float(str)
except ValueError:
number = 0.0
# you can assign an appropriate value instead of 0.0 which suits your requirement
return number
现在你可以用这个新函数来替代内置的浮点数函数,方法如下:
v4.append(str_to_float(fields[3]))