简体   繁体   English

使用xarray的open_mfdataset打开一系列.nc文件

[英]Using xarray's open_mfdataset to open a series of .nc files

I have a series of files named 0.nc, 1.nc, 2.nc, ... and am looking to use open_mfdataset to open them all at once, in order of filename.我有一系列名为 0.nc、1.nc、2.nc 的文件,我希望使用 open_mfdataset 按文件名顺序一次打开它们。 However, when I run the command:但是,当我运行命令时:

labels = xarray.open_mfdataset('*.nc')

I get the error我得到错误

ValueError: Could not find any dimension coordinates to use to order the datasets for concatenation

I have tried adding a coordinate by:我尝试通过以下方式添加坐标:

for i in range(0,10):
    labels = xarray.open_dataset(f'{i}.nc')
    labels = labels.assign_coords({'name' : i})
    labels.to_netcdf(f'.{i}_named.nc')

And then loading those files, but to no avail (same error).然后加载这些文件,但无济于事(同样的错误)。

What is a way I can load these files as one dataset where I dont encounter these errors?有什么方法可以将这些文件作为一个数据集加载,而不会遇到这些错误?

When you call open_mfdataset without any arguments, xarray attempts to automatically infer the structure of your data and the way you would like to concatenate it.当您在没有任何 arguments 的情况下调用open_mfdataset时,xarray 会尝试自动推断您的数据结构以及您想要连接它的方式。 In some cases, such as this one, the automatic inference fails.在某些情况下,例如本例,自动推理会失败。 You can resolve this by providing more explicit instructions to tell xarray how to concatenate the data.您可以通过提供更明确的说明来告诉 xarray 如何连接数据来解决此问题。

See the docs on combining data , which define the important concepts and describe many of the arguments you'll use, and then check out the arguments to xr.open_mfdataset - specifically, provide the combine and concat_dim arguments.请参阅有关合并数据的文档,其中定义了重要概念并描述了您将使用的许多 arguments,然后查看 arguments 到xr.open_mfdataset - 具体来说,提供combineconcat_dim arguments。

For example, you might provide:例如,您可以提供:

ds = xarray.open_mfdataset(
    [f'{i}.nc' for i in range(10)],
    concat_dim=[
        pd.Index(np.arange(10), name="new_dim"),
    ],
    combine="nested",

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM