How to preprocess dataset to assign coordinates before opening with xarray.open_mfdataset?

The xarray documentation for the open_mfdataset function states that you can use the preprocess argument to apply a function to each dataset before concatenation. The NetCDF datasets I have do not have coordinates assigned when you open them one-by-one, so I was attempting to assign them before concatenation with combine='by_coords' in the open_mfdataset function.

This is what a single one of the datasets looks like if you open it:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>path = 'path/to/my/file/file.nc'
ds = xr.open_dataset(path, decode_times=False)
ds
# <xarray.Dataset> Size: 1GB
# Dimensions: (comid: 2677612, time_mn: 120, time_yr: 10)
# Dimensions without coordinates: comid, time_mn, time_yr
#Data variables:
# COMID (comid) int32 11MB ...
# Time_mn (time_mn) int32 480B ...
# Time_yr (time_yr) int32 40B ...
# RAPID_mn_cfs (comid, time_mn) float32 1GB ...
# RAPID_yr_cfs (comid, time_yr) float32 107MB ...
</code>
<code>path = 'path/to/my/file/file.nc' ds = xr.open_dataset(path, decode_times=False) ds # <xarray.Dataset> Size: 1GB # Dimensions: (comid: 2677612, time_mn: 120, time_yr: 10) # Dimensions without coordinates: comid, time_mn, time_yr #Data variables: # COMID (comid) int32 11MB ... # Time_mn (time_mn) int32 480B ... # Time_yr (time_yr) int32 40B ... # RAPID_mn_cfs (comid, time_mn) float32 1GB ... # RAPID_yr_cfs (comid, time_yr) float32 107MB ... </code>
path = 'path/to/my/file/file.nc'
ds = xr.open_dataset(path, decode_times=False)
ds

# <xarray.Dataset> Size: 1GB
# Dimensions:       (comid: 2677612, time_mn: 120, time_yr: 10)
# Dimensions without coordinates: comid, time_mn, time_yr
#Data variables:
#    COMID         (comid) int32 11MB ...
#    Time_mn       (time_mn) int32 480B ...
#    Time_yr       (time_yr) int32 40B ...
#    RAPID_mn_cfs  (comid, time_mn) float32 1GB ...
#    RAPID_yr_cfs  (comid, time_yr) float32 107MB ...

To use open_mfdataset my code looks like this. The assignCoordinates function works as intended, but it still fails to open the datasets.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def assignCoordinates(df):
df = df.assign_coords({
"comid": df['COMID'],
"time_mn": fd.calcDatetimes(df, 'Time_mn', df.sizes['time_mn']), #this just calculates datetimes for the weird time units used in these files, the function works properly
"time_yr": fd.calcDatetimes(df, 'Time_yr', df.sizes['time_yr'])
})
return df
path = "path/to/files/*.nc"
ds = xr.open_mfdataset(path, preprocess=assignCoordinates, combine='by_coords', decode_times=False)
ds
</code>
<code>def assignCoordinates(df): df = df.assign_coords({ "comid": df['COMID'], "time_mn": fd.calcDatetimes(df, 'Time_mn', df.sizes['time_mn']), #this just calculates datetimes for the weird time units used in these files, the function works properly "time_yr": fd.calcDatetimes(df, 'Time_yr', df.sizes['time_yr']) }) return df path = "path/to/files/*.nc" ds = xr.open_mfdataset(path, preprocess=assignCoordinates, combine='by_coords', decode_times=False) ds </code>
def assignCoordinates(df):
    df = df.assign_coords({
        "comid": df['COMID'], 
        "time_mn": fd.calcDatetimes(df, 'Time_mn', df.sizes['time_mn']), #this just calculates datetimes for the weird time units used in these files, the function works properly
        "time_yr": fd.calcDatetimes(df, 'Time_yr', df.sizes['time_yr'])
    })
    return df

path = "path/to/files/*.nc"
ds = xr.open_mfdataset(path, preprocess=assignCoordinates, combine='by_coords', decode_times=False)

ds

This is the error I receive:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>ValueError: Could not find any dimension coordinates to use to order the datasets for concatenation
</code>
<code>ValueError: Could not find any dimension coordinates to use to order the datasets for concatenation </code>
ValueError: Could not find any dimension coordinates to use to order the datasets for concatenation

I assume the preprocessed files are not actually being used by open_mfdataset, but then I don’t really understand what the point of that argument is. My suspicion that it doesn’t use the preprocessed datasets is further enforced by the fact that if it was, I should be able to remove decode_times=False because the times are now calculated in a way that makes sense and could be decoded after running through the assignCoordinates function, but if I remove it, I get an error about the times being unable to be decoded.

Is there a way to do what I am wanting or do I really have to open each dataset individually?

Minimum Reproducible Example

Copy this code, and fill out the export path. This will create three .nc files in the directory you specify.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import xarray as xr
import numpy as np
np.random.seed(0)
temperature = 15 + 8 * np.random.randn(2, 3, 4)
precipitation = 10 * np.random.rand(2, 3, 4)
lon = [-99.83, -99.32]
lat = [42.25, 42.21]
instruments = ["manufac1", "manufac2", "manufac3"]
time = pd.date_range("2014-09-06", periods=4)
reference_time = pd.Timestamp("2014-09-05")
ds = xr.Dataset(
data_vars=dict(
temperature=(["loc", "instrument", "time"], temperature),
precipitation=(["loc", "instrument", "time"], precipitation),
),
attrs=dict(description="Weather related data."),
)
for i in range(1,4):
ds.to_netcdf(f'yourdirectory/test{i}.nc') #### EDIT HERE #####
</code>
<code>import xarray as xr import numpy as np np.random.seed(0) temperature = 15 + 8 * np.random.randn(2, 3, 4) precipitation = 10 * np.random.rand(2, 3, 4) lon = [-99.83, -99.32] lat = [42.25, 42.21] instruments = ["manufac1", "manufac2", "manufac3"] time = pd.date_range("2014-09-06", periods=4) reference_time = pd.Timestamp("2014-09-05") ds = xr.Dataset( data_vars=dict( temperature=(["loc", "instrument", "time"], temperature), precipitation=(["loc", "instrument", "time"], precipitation), ), attrs=dict(description="Weather related data."), ) for i in range(1,4): ds.to_netcdf(f'yourdirectory/test{i}.nc') #### EDIT HERE ##### </code>
import xarray as xr 
import numpy as np

np.random.seed(0)
temperature = 15 + 8 * np.random.randn(2, 3, 4)
precipitation = 10 * np.random.rand(2, 3, 4)
lon = [-99.83, -99.32]
lat = [42.25, 42.21]
instruments = ["manufac1", "manufac2", "manufac3"]
time = pd.date_range("2014-09-06", periods=4)
reference_time = pd.Timestamp("2014-09-05")
ds = xr.Dataset(
    data_vars=dict(
        temperature=(["loc", "instrument", "time"], temperature),
        precipitation=(["loc", "instrument", "time"], precipitation),
    ),
    attrs=dict(description="Weather related data."),
)
for i in range(1,4):
    ds.to_netcdf(f'yourdirectory/test{i}.nc') #### EDIT HERE #####

After doing the above, run this code (remember to alter the directory to where you saved the files created above):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def assignCoordinates(df):
df = df.assign_coords({
"loc": df['loc'],
"instrument": df['instrument'],
"time": df['time']
})
return df
ds = xarr.open_mfdataset('yourdirectory/*.nc', preprocess=assignCoordinates, combine='by_coords') #### EDIT HERE #####
ds
</code>
<code>def assignCoordinates(df): df = df.assign_coords({ "loc": df['loc'], "instrument": df['instrument'], "time": df['time'] }) return df ds = xarr.open_mfdataset('yourdirectory/*.nc', preprocess=assignCoordinates, combine='by_coords') #### EDIT HERE ##### ds </code>
def assignCoordinates(df):
    df = df.assign_coords({
        "loc": df['loc'],
        "instrument": df['instrument'],
        "time": df['time']
    })
    return df

ds = xarr.open_mfdataset('yourdirectory/*.nc', preprocess=assignCoordinates, combine='by_coords') #### EDIT HERE #####
ds

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật