我正在努力将几个 Berkeley Earth netCDF 文件转换为 CSV 或其他表格格式。我意识到以前也有人提出过类似的问题,但我无法应用我遇到的任何解决方案。
例如,这个数据集.
ncdump
似乎没有生成实际的 CSV 文件。我找不到任何关于如何这样做的说明。pandas
将数据加载到 xarray.to_dataframe()
数据帧中,但我的笔记本无法分配所需的内存。In [1]: import xarray as xr
In [2]: import pandas as pd
In [3]: nc = xr.open_dataset('Complete_TAVG_Daily_EqualArea.nc')
In [4]: nc
Out[4]:
<xarray.Dataset>
Dimensions: (map_points: 5498, time: 50769)
Dimensions without coordinates: map_points, time
Data variables:
longitude (map_points) float32 ...
latitude (map_points) float32 ...
date_number (time) float64 ...
year (time) float64 ...
month (time) float64 ...
day (time) float64 ...
day_of_year (time) float64 ...
land_mask (map_points) float64 ...
In [5]: df = nc.to_dataframe()
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
(...)
MemoryError: Unable to allocate 532. MiB for an array with shape (279127962,) and data type int16
Panoply
转换。 CSV 导出似乎只能将单个变量(我想将其视为一列)导出到单行文件中。我一定是漏了什么。有人可以帮助我吗?
您缺少的是 netCDF 是一种比 CSV 复杂得多的格式。一个 netCDF 文件可以包含多个任意形状和大小的数组。 CSV 文件只能包含一个最大二维数组(或一组一维数组,如果它们的长度都相同)。因此,您不能简单地将任何 netCDF 文件转换为 CSV。
让我们看一下您提供的示例文件。我在这里用我的 Xarray 版本重复信息,这似乎有点冗长......
In [16]: ds = xr.open_dataset('Complete_TAVG_EqualArea.nc')
In [17]: ds
Out[17]:
<xarray.Dataset>
Dimensions: (map_points: 5498, month_number: 12, time: 3240)
Coordinates:
longitude (map_points) float32 ...
latitude (map_points) float32 ...
* time (time) float64 1.75e+03 1.75e+03 1.75e+03 ... 2.02e+03 2.02e+03
Dimensions without coordinates: map_points, month_number
Data variables:
land_mask (map_points) float64 ...
temperature (time, map_points) float32 ...
climatology (month_number, map_points) float32 ...
Attributes:
Conventions: Berkeley Earth Internal Convention (based on CF-1.5)
title: Native Format Berkeley Earth Surface Temperature An...
history: 16-Jan-2020 06:51:38
institution: Berkeley Earth Surface Temperature Project
source_file: Complete_TAVG.50985s.20200116T064041.mat
source_history: 13-Jan-2020 17:22:52
source_data_version: ca6f26341938dae0ea7dd619bce6f15e
comment: This file contains Berkeley Earth surface temperatu...
有三个数据变量(land_mask, temperature, climatology),加上三个坐标向量(longitude, latitude, time)。也许您可以将坐标向量包含在 CSV 文件的第一行和第一列,但即便如此,这也意味着每个 netCDF 文件至少需要三个单独的 CSV 文件。
因此,例如对于
climatology
数据框,您可以按如下方式写入CSV:
In [31]: clim = ds['climatology']
In [32]: clim.to_pandas().to_csv('clim.csv')
所以
clim
是一个xarray.DataFrame
,原则上可以写入CSV文件。不幸的是,xarray.DataFrame
类没有 to_csv
方法。然而 pandas.DataFrame
类,所以我们首先将它转换为 pandas 数据框。查看其参数文档 here 以调整生成的输出文件。
您可以使用 CDO 软件包套件将 .nc 转换为 .csv。
示例代码(您需要编辑一些 outputtab 参数:
cdo -outputtab,date,lon,lat,value infile.nc | awk 'FNR==1{ row=$2","$3","$4","$5;print row } FNR!=1{ row=$1","$2","$3","$4; print row}' > outfile.csv