The error occurs because some variables in the dataset have non-numeric data types (like strings or datetime objects). Here's a revised version that handles this:
import xarray as xr
import numpy as np
# Load the dataset
ds = xr.open_dataset('unet_conf_seed_7.eam.h2.0002-12-30-03600.nc')
# Check each variable for NaN and inf values
print("Checking for NaN/inf values in all variables:\n")
for var in ds.variables:
data = ds[var].values
# Check if the data type is numeric
if np.issubdtype(data.dtype, np.number):
nan_count = np.isnan(data).sum()
inf_count = np.isinf(data).sum()
if nan_count > 0 or inf_count > 0:
print(f"❌ {var}: {nan_count} NaN, {inf_count} inf")
else:
print(f"✓ {var}: OK")
else:
print(f"- {var}: non-numeric dtype ({data.dtype})")
# Quick summary
numeric_vars = [var for var in ds.variables
if np.issubdtype(ds[var].values.dtype, np.number)]
problem_vars = sum(1 for var in numeric_vars
if np.isnan(ds[var].values).any() or np.isinf(ds[var].values).any())
print(f"\nSummary: {problem_vars}/{len(numeric_vars)} numeric variables have NaN/inf values")
Alternatively, you can use a try-except approach:
for var in ds.variables:
try:
data = ds[var].values
nan_count = np.isnan(data).sum()
inf_count = np.isinf(data).sum()
if nan_count > 0 or inf_count > 0:
print(f"❌ {var}: {nan_count} NaN, {inf_count} inf")
else:
print(f"✓ {var}: OK")
except TypeError:
print(f"- {var}: non-numeric dtype ({ds[var].dtype})")
This will skip over coordinate variables like time, lat, lon that might be stored as non-numeric types.