【问题标题】:convert csv to netcdf将csv转换为netcdf
【发布时间】:2014-05-20 23:04:28
【问题描述】:

我正在尝试通过 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

#convert 到 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',))

# 将单位属性分配给坐标 var 数据。这将文本属性附加到每个坐标变量,包含单位。

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: 

【问题讨论】:

  • 错误提示fields[3] 中的值不是数字,因此无法转换为浮点数。检查您的输入文件中的该值。您还可以尝试打印fields[3] 的值,然后再将其转换为浮点数并添加到列表v4
  • 非常感谢您澄清这一点。你是对的,只需打印它就可以了,但我不相信它在进入 netcdf 时会很好地传输。这些是纬度,因此通过为它们分配任何数据类型,在转移到 netcdf 时可以吗?

标签: python csv netcdf


【解决方案1】:

虽然上面提到的xarray 是一个很棒的工具,但英国气象局的iris 库也值得一看。 Iris 的一个关键优势是有助于创建遵循气候预测(CF 约定)的 netCDF 文件。它通过提供帮助函数来定义standard names、单位、坐标系和其他元数据约定来实现这一点。它还提供绘图、子集和分析实用程序。

对于这样的地球科学数据,CF 是recommended standard for netCDF files

作为其使用示例,this Python notebook 重新实现了上面的 AO/NAO 示例。

【讨论】:

  • iris 可能很难安装,但如果您使用 Anaconda,则可以通过 Anaconda.org/conda-forge 频道使用 conda install -c conda-forge iris 安装它
【解决方案2】:

这对于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

【讨论】:

  • pandas.errors.ParserError: Expected 21 fields in line 10, saw 22. 错误可能是由于使用多字符分隔符时忽略引号引起的。
【解决方案3】:

如果您看到输入文件,则第二行中的 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

现在你可以用这个函数代替内置的 float 函数了:

v4.append(str_to_float(fields[3]))

【讨论】:

  • 看看this SO question,它可以更深入地了解字符串到整数或浮点数的转换。
  • 非常感谢您的详尽解释。我没有意识到它将它存储为一个空字符串。这种新方法很有意义,而且效果很好。
  • 能否询问此问题第 2 部分的可能解决方案?是否有任何资源可以更清楚地说明如何将上述 .csv 文件中的声明变量导入 netCDF4 文件?从 .csv 到 netcdf 的转换似乎没有很多信息。我一直在用 v (1,2,3...等) 变量替换 press_out、temp_out、lats 和 lons,但它没有注册我试图转换为 netcdf4 格式的信息。您能提供任何额外的帮助吗?
  • 对不起。我不熟悉netCDF4。我认为您应该将此问题视为 2 个子问题:1. 从 csv 读取数据,将其存储在变量中。(您已经完成了)2. 使用存储在变量中的这些数据将它们提供给 netCDF 变量。我认为您应该检查第二部分的documentation。如果您在执行此操作时遇到任何错误,请发布错误以便确定错误的原因。
  • 感谢您的帮助!
猜你喜欢
  • 2019-12-17
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 2022-07-29
  • 2015-05-19
  • 2018-05-10
  • 2013-03-04
  • 1970-01-01
相关资源
最近更新 更多