Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

access and change Variable attrs

24 views
Skip to first unread message

André Lisboa

unread,
Jul 14, 2023, 12:51:22 PM7/14/23
to xarray
Hi,

How can one change the Variable attrs?

As explicit in the documentation, this is silent, and does not affec the attrs:
m.variables['Link-p'].sel(Link='test_1').attrs['integer'] = True

The solution mentioned  in the docs does not work for Variables (at least I am not able). How can one change the attrs value?

Thank you in advance,
André Lisboa

Marco Miani

unread,
Jul 15, 2023, 4:30:21 AM7/15/23
to xarray
Hi there.


I am creating a test dataset, as illustrated on the official webpage:
https://docs.xarray.dev/en/stable/generated/xarray.Dataset.html

import numpy as np
import pandas as pd
import xarray as xr


np.random.seed(0)
temperature = 15 + 8 * np.random.randn(2, 2, 3)
precipitation = 10 * np.random.rand(2, 2, 3)
lon = [[-99.83, -99.32], [-99.79, -99.23]]
lat = [[42.25, 42.21], [42.63, 42.59]]
time = pd.date_range("2014-09-06", periods=3)
reference_time = pd.Timestamp("2014-09-05")


ds = xr.Dataset(
    data_vars=dict(
        temperature=(["x", "y", "time"], temperature),
        precipitation=(["x", "y", "time"], precipitation),
    ),
    coords=dict(
        lon=(["x", "y"], lon),
        lat=(["x", "y"], lat),
        time=time,
        reference_time=reference_time,
    ),
    attrs=dict(description="Weather related data."),
)


#This is to add/edit metadata and works all right for me
ds.temperature.attrs['name'] = 'some strange temeprature'
ds.temperature.attrs['units'] = 'apples'


print(ds.temperature)

# <xarray.DataArray 'temperature' (x: 2, y: 2, time: 3)>
# array([[[29.11241877, 18.20125767, 22.82990387],
#         [32.92714559, 29.94046392,  7.18177696]],

#        [[22.60070734, 13.78914233, 14.17424919],
#         [18.28478802, 16.15234857, 26.63418806]]])
# Coordinates:
#     lon             (x, y) float64 -99.83 -99.32 -99.79 -99.23
#     lat             (x, y) float64 42.25 42.21 42.63 42.59
#   * time            (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
#     reference_time  datetime64[ns] 2014-09-05
# Dimensions without coordinates: x, y
# Attributes:
#     name:     some strange temeprature
#     units:    apples


Hope this helps.
Bye
M
Reply all
Reply to author
Forward
0 new messages