Skip to content

Xarray

print_ds_var_list(ds, phrase=None)

Prints all variables in ds which contain phrase in the variable name or variable long_name.

Parameters:

Name Type Description Default
ds Dataset

Dataset to investigate variables of.

required
phrase Optional[str]

Key phrase to search for in variable info.

None
Source code in isca_tools/utils/xarray.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def print_ds_var_list(ds: xr.Dataset, phrase: Optional[str] = None) -> None:
    """
    Prints all variables in `ds` which contain `phrase` in the variable name or variable `long_name`.

    Args:
        ds: Dataset to investigate variables of.
        phrase: Key phrase to search for in variable info.

    """
    # All the exceptions to deal with case when var does not have a long_name
    var_list = list(ds.keys())
    if phrase is None:
        for var in var_list:
            try:
                print(f'{var}: {ds[var].long_name}')
            except AttributeError:
                print(f'{var}')
    else:
        for var in var_list:
            if phrase.lower() in var.lower():
                try:
                    print(f'{var}: {ds[var].long_name}')
                except AttributeError:
                    print(f'{var}')
                continue
            try:
                if phrase.lower() in ds[var].long_name.lower():
                    print(f'{var}: {ds[var].long_name}')
                    continue
            except AttributeError:
                continue
    return None

set_attrs(var, overwrite=True, **kwargs)

Set attributes of a given variable.

Examples:

set_attrs(ds.plev, long_name='pressure', units='Pa')

Parameters:

Name Type Description Default
var DataArray

Variable to set attributes of.

required
overwrite bool

If True, overwrite existing attributes, otherwise leave unchanged.

True
**kwargs str

Attributes to set. Common ones include long_name and units

{}

Returns:

Type Description
DataArray

var with attributes set.

Source code in isca_tools/utils/xarray.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def set_attrs(var: xr.DataArray, overwrite: bool = True, **kwargs: str) -> xr.DataArray:
    """
    Set attributes of a given variable.

    Examples:
        `set_attrs(ds.plev, long_name='pressure', units='Pa')`

    Args:
        var: Variable to set attributes of.
        overwrite: If `True`, overwrite existing attributes, otherwise leave unchanged.
        **kwargs: Attributes to set. Common ones include `long_name` and `units`

    Returns:
        `var` with attributes set.
    """
    # Function to set main attributes of given variable
    for key in kwargs:
        if (key in var.attrs) and not overwrite:
            continue
        var.attrs[key] = kwargs[key]
    return var