Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through dataArray attributes in an xarray dataset

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?

like image 858
user2118915 Avatar asked Jul 26 '26 22:07

user2118915


1 Answers

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.

like image 164
jhamman Avatar answered Jul 29 '26 12:07

jhamman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!