I have an xarray dataset, which contains many dataArrays. Each of these dataArrays have a .attrs which contains an ordered dict with ] things like the description and units of each dataArray.
I would like to loop through each dataArray in the dataSet and print each of their .attrs out.
for ii in dataSet.data_vars:
print(ii)
will give me the name of each dataArray. However, when I try
for ii in dataSet.data_vars:
print(ii.attrs)
I get AttributeError: 'str' object has no attribute 'attrs' If I try instead,
for ii in dataSet.data_vars:
print(dataSet.ii.attrs)
I get AttributeError: 'Dataset' object has no attribute 'ii'
It would seem that python is trying to read 'ii' as a DataArray name instead of the actual dataArray name stored as a string under ii. How can I go about looping through all the dataArrays and printing out the [dataArray].attrs of each one?
data_vars is a dictionary that you can iterate over key,value pairs.
for varname, da in dataSet.data_vars.items():
print(da.attrs)
You're last example would also work but you need to use ii as dictionary key:
for ii in dataSet.data_vars:
print(dataSet[ii].attrs)
Note, if you're using a recent version of xarray, you can also print all the variables/attributes using the dataSet.info() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With