您缺少的是 netCDF 是一种比 CSV 复杂得多的格式。 netCDF 文件可以包含任意形状和大小的多个数组。 CSV 文件只能包含最大 2 维的单个数组(或一组一维数组,如果它们都具有相同的长度)。因此,您不能简单地将任何 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、温度、气候),加上三个坐标向量(经度、纬度、时间)。也许您可以将坐标向量包含为 CSV 文件的第一行和第一列,但即便如此,这也意味着每个 netCDF 文件至少需要三个单独的 CSV 文件。
例如对于climatology
您可以将数据框写入 CSV,如下所示:
In [31]: clim = ds['climatology']
In [32]: clim.to_pandas().to_csv('clim.csv')
So clim
is an xarray.DataFrame
原则上可以写入 CSV 文件。不幸的是xarray.DataFrame
类没有to_csv
方法。但是,那pandas.DataFrame
类确实如此,所以我们首先将其转换为 pandas 数据框。看它的参数文档here https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html调整生成的输出文件。