gpt4 book ai didi

python - 将 csv 转换为 netcdf

转载 作者:太空狗 更新时间:2023-10-30 01:51:16 24 4
gpt4 key购买 nike

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

最佳答案

这对 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 Distribution,则可以从 Anaconda.org/conda-forge channel 安装它通过使用:

conda install -c conda-forge xarray

关于python - 将 csv 转换为 netcdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22933855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com