-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathdataarray.py
5760 lines (5034 loc) · 209 KB
/
dataarray.py
1
2
3
4
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import warnings
from os import PathLike
from typing import (
TYPE_CHECKING,
Any,
Callable,
Hashable,
Iterable,
Literal,
Mapping,
NoReturn,
Sequence,
cast,
overload,
)
import numpy as np
import pandas as pd
from ..coding.calendar_ops import convert_calendar, interp_calendar
from ..coding.cftimeindex import CFTimeIndex
from ..plot.plot import _PlotMethods
from ..plot.utils import _get_units_from_attrs
from . import alignment, computation, dtypes, indexing, ops, utils
from ._reductions import DataArrayReductions
from .accessor_dt import CombinedDatetimelikeAccessor
from .accessor_str import StringAccessor
from .alignment import _broadcast_helper, _get_broadcast_dims_map_common_coords, align
from .arithmetic import DataArrayArithmetic
from .common import AbstractArray, DataWithCoords, get_chunksizes
from .computation import unify_chunks
from .coordinates import DataArrayCoordinates, assert_coordinate_consistent
from .dataset import Dataset
from .formatting import format_item
from .indexes import (
Index,
Indexes,
PandasMultiIndex,
filter_indexes_from_coords,
isel_indexes,
)
from .indexing import is_fancy_indexer, map_index_queries
from .merge import PANDAS_TYPES, MergeError, _create_indexes_from_coords
from .npcompat import QUANTILE_METHODS, ArrayLike
from .options import OPTIONS, _get_keep_attrs
from .utils import (
Default,
HybridMappingProxy,
ReprObject,
_default,
either_dict_or_kwargs,
)
from .variable import IndexVariable, Variable, as_compatible_data, as_variable
if TYPE_CHECKING:
from typing import TypeVar, Union
try:
from dask.delayed import Delayed
except ImportError:
Delayed = None # type: ignore
try:
from cdms2 import Variable as cdms2_Variable
except ImportError:
cdms2_Variable = None
try:
from iris.cube import Cube as iris_Cube
except ImportError:
iris_Cube = None
from ..backends.api import T_NetcdfEngine, T_NetcdfTypes
from .groupby import DataArrayGroupBy
from .resample import DataArrayResample
from .rolling import DataArrayCoarsen, DataArrayRolling
from .types import (
CoarsenBoundaryOptions,
DatetimeUnitOptions,
ErrorOptions,
ErrorOptionsWithWarn,
InterpOptions,
PadModeOptions,
PadReflectOptions,
QueryEngineOptions,
QueryParserOptions,
ReindexMethodOptions,
SideOptions,
T_DataArray,
T_Xarray,
)
from .weighted import DataArrayWeighted
T_XarrayOther = TypeVar("T_XarrayOther", bound=Union["DataArray", Dataset])
def _infer_coords_and_dims(
shape, coords, dims
) -> tuple[dict[Hashable, Variable], tuple[Hashable, ...]]:
"""All the logic for creating a new DataArray"""
if (
coords is not None
and not utils.is_dict_like(coords)
and len(coords) != len(shape)
):
raise ValueError(
f"coords is not dict-like, but it has {len(coords)} items, "
f"which does not match the {len(shape)} dimensions of the "
"data"
)
if isinstance(dims, str):
dims = (dims,)
if dims is None:
dims = [f"dim_{n}" for n in range(len(shape))]
if coords is not None and len(coords) == len(shape):
# try to infer dimensions from coords
if utils.is_dict_like(coords):
dims = list(coords.keys())
else:
for n, (dim, coord) in enumerate(zip(dims, coords)):
coord = as_variable(coord, name=dims[n]).to_index_variable()
dims[n] = coord.name
dims = tuple(dims)
elif len(dims) != len(shape):
raise ValueError(
"different number of dimensions on data "
f"and dims: {len(shape)} vs {len(dims)}"
)
else:
for d in dims:
if not isinstance(d, str):
raise TypeError(f"dimension {d} is not a string")
new_coords: dict[Hashable, Variable] = {}
if utils.is_dict_like(coords):
for k, v in coords.items():
new_coords[k] = as_variable(v, name=k)
elif coords is not None:
for dim, coord in zip(dims, coords):
var = as_variable(coord, name=dim)
var.dims = (dim,)
new_coords[dim] = var.to_index_variable()
sizes = dict(zip(dims, shape))
for k, v in new_coords.items():
if any(d not in dims for d in v.dims):
raise ValueError(
f"coordinate {k} has dimensions {v.dims}, but these "
"are not a subset of the DataArray "
f"dimensions {dims}"
)
for d, s in zip(v.dims, v.shape):
if s != sizes[d]:
raise ValueError(
f"conflicting sizes for dimension {d!r}: "
f"length {sizes[d]} on the data but length {s} on "
f"coordinate {k!r}"
)
if k in sizes and v.shape != (sizes[k],):
raise ValueError(
f"coordinate {k!r} is a DataArray dimension, but "
f"it has shape {v.shape!r} rather than expected shape {sizes[k]!r} "
"matching the dimension size"
)
return new_coords, dims
def _check_data_shape(data, coords, dims):
if data is dtypes.NA:
data = np.nan
if coords is not None and utils.is_scalar(data, include_0d=False):
if utils.is_dict_like(coords):
if dims is None:
return data
else:
data_shape = tuple(
as_variable(coords[k], k).size if k in coords.keys() else 1
for k in dims
)
else:
data_shape = tuple(as_variable(coord, "foo").size for coord in coords)
data = np.full(data_shape, data)
return data
class _LocIndexer:
__slots__ = ("data_array",)
def __init__(self, data_array: DataArray):
self.data_array = data_array
def __getitem__(self, key) -> DataArray:
if not utils.is_dict_like(key):
# expand the indexer so we can handle Ellipsis
labels = indexing.expanded_indexer(key, self.data_array.ndim)
key = dict(zip(self.data_array.dims, labels))
return self.data_array.sel(key)
def __setitem__(self, key, value) -> None:
if not utils.is_dict_like(key):
# expand the indexer so we can handle Ellipsis
labels = indexing.expanded_indexer(key, self.data_array.ndim)
key = dict(zip(self.data_array.dims, labels))
dim_indexers = map_index_queries(self.data_array, key).dim_indexers
self.data_array[dim_indexers] = value
# Used as the key corresponding to a DataArray's variable when converting
# arbitrary DataArray objects to datasets
_THIS_ARRAY = ReprObject("<this-array>")
class DataArray(
AbstractArray, DataWithCoords, DataArrayArithmetic, DataArrayReductions
):
"""N-dimensional array with labeled coordinates and dimensions.
DataArray provides a wrapper around numpy ndarrays that uses
labeled dimensions and coordinates to support metadata aware
operations. The API is similar to that for the pandas Series or
DataFrame, but DataArray objects can have any number of dimensions,
and their contents have fixed data types.
Additional features over raw numpy arrays:
- Apply operations over dimensions by name: ``x.sum('time')``.
- Select or assign values by integer location (like numpy):
``x[:10]`` or by label (like pandas): ``x.loc['2014-01-01']`` or
``x.sel(time='2014-01-01')``.
- Mathematical operations (e.g., ``x - y``) vectorize across
multiple dimensions (known in numpy as "broadcasting") based on
dimension names, regardless of their original order.
- Keep track of arbitrary metadata in the form of a Python
dictionary: ``x.attrs``
- Convert to a pandas Series: ``x.to_series()``.
Getting items from or doing mathematical operations with a
DataArray always returns another DataArray.
Parameters
----------
data : array_like
Values for this array. Must be an ``numpy.ndarray``, ndarray
like, or castable to an ``ndarray``. If a self-described xarray
or pandas object, attempts are made to use this array's
metadata to fill in other unspecified arguments. A view of the
array's data is used instead of a copy if possible.
coords : sequence or dict of array_like, optional
Coordinates (tick labels) to use for indexing along each
dimension. The following notations are accepted:
- mapping {dimension name: array-like}
- sequence of tuples that are valid arguments for
``xarray.Variable()``
- (dims, data)
- (dims, data, attrs)
- (dims, data, attrs, encoding)
Additionally, it is possible to define a coord whose name
does not match the dimension name, or a coord based on multiple
dimensions, with one of the following notations:
- mapping {coord name: DataArray}
- mapping {coord name: Variable}
- mapping {coord name: (dimension name, array-like)}
- mapping {coord name: (tuple of dimension names, array-like)}
dims : Hashable or sequence of Hashable, optional
Name(s) of the data dimension(s). Must be either a Hashable
(only for 1D data) or a sequence of Hashables with length equal
to the number of dimensions. If this argument is omitted,
dimension names are taken from ``coords`` (if possible) and
otherwise default to ``['dim_0', ... 'dim_n']``.
name : str or None, optional
Name of this array.
attrs : dict_like or None, optional
Attributes to assign to the new instance. By default, an empty
attribute dictionary is initialized.
Examples
--------
Create data:
>>> np.random.seed(0)
>>> temperature = 15 + 8 * np.random.randn(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")
Initialize a dataarray with multiple dimensions:
>>> da = xr.DataArray(
... data=temperature,
... dims=["x", "y", "time"],
... coords=dict(
... lon=(["x", "y"], lon),
... lat=(["x", "y"], lat),
... time=time,
... reference_time=reference_time,
... ),
... attrs=dict(
... description="Ambient temperature.",
... units="degC",
... ),
... )
>>> da
<xarray.DataArray (x: 2, y: 2, time: 3)>
array([[[29.11241877, 18.20125767, 22.82990387],
[32.92714559, 29.94046392, 7.18177696]],
<BLANKLINE>
[[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:
description: Ambient temperature.
units: degC
Find out where the coldest temperature was:
>>> da.isel(da.argmin(...))
<xarray.DataArray ()>
array(7.18177696)
Coordinates:
lon float64 -99.32
lat float64 42.21
time datetime64[ns] 2014-09-08
reference_time datetime64[ns] 2014-09-05
Attributes:
description: Ambient temperature.
units: degC
"""
_cache: dict[str, Any]
_coords: dict[Any, Variable]
_close: Callable[[], None] | None
_indexes: dict[Hashable, Index]
_name: Hashable | None
_variable: Variable
__slots__ = (
"_cache",
"_coords",
"_close",
"_indexes",
"_name",
"_variable",
"__weakref__",
)
dt = utils.UncachedAccessor(CombinedDatetimelikeAccessor["DataArray"])
def __init__(
self,
data: Any = dtypes.NA,
coords: Sequence[Sequence[Any] | pd.Index | DataArray]
| Mapping[Any, Any]
| None = None,
dims: Hashable | Sequence[Hashable] | None = None,
name: Hashable = None,
attrs: Mapping = None,
# internal parameters
indexes: dict[Hashable, Index] = None,
fastpath: bool = False,
) -> None:
if fastpath:
variable = data
assert dims is None
assert attrs is None
assert indexes is not None
else:
# TODO: (benbovy - explicit indexes) remove
# once it becomes part of the public interface
if indexes is not None:
raise ValueError("Providing explicit indexes is not supported yet")
# try to fill in arguments from data if they weren't supplied
if coords is None:
if isinstance(data, DataArray):
coords = data.coords
elif isinstance(data, pd.Series):
coords = [data.index]
elif isinstance(data, pd.DataFrame):
coords = [data.index, data.columns]
elif isinstance(data, (pd.Index, IndexVariable)):
coords = [data]
if dims is None:
dims = getattr(data, "dims", getattr(coords, "dims", None))
if name is None:
name = getattr(data, "name", None)
if attrs is None and not isinstance(data, PANDAS_TYPES):
attrs = getattr(data, "attrs", None)
data = _check_data_shape(data, coords, dims)
data = as_compatible_data(data)
coords, dims = _infer_coords_and_dims(data.shape, coords, dims)
variable = Variable(dims, data, attrs, fastpath=True)
indexes, coords = _create_indexes_from_coords(coords)
# These fully describe a DataArray
self._variable = variable
assert isinstance(coords, dict)
self._coords = coords
self._name = name
# TODO(shoyer): document this argument, once it becomes part of the
# public interface.
self._indexes = indexes # type: ignore[assignment]
self._close = None
@classmethod
def _construct_direct(
cls: type[T_DataArray],
variable: Variable,
coords: dict[Any, Variable],
name: Hashable,
indexes: dict[Hashable, Index],
) -> T_DataArray:
"""Shortcut around __init__ for internal use when we want to skip
costly validation
"""
obj = object.__new__(cls)
obj._variable = variable
obj._coords = coords
obj._name = name
obj._indexes = indexes
obj._close = None
return obj
def _replace(
self: T_DataArray,
variable: Variable = None,
coords=None,
name: Hashable | None | Default = _default,
indexes=None,
) -> T_DataArray:
if variable is None:
variable = self.variable
if coords is None:
coords = self._coords
if indexes is None:
indexes = self._indexes
if name is _default:
name = self.name
return type(self)(variable, coords, name=name, indexes=indexes, fastpath=True)
def _replace_maybe_drop_dims(
self: T_DataArray,
variable: Variable,
name: Hashable | None | Default = _default,
) -> T_DataArray:
if variable.dims == self.dims and variable.shape == self.shape:
coords = self._coords.copy()
indexes = self._indexes
elif variable.dims == self.dims:
# Shape has changed (e.g. from reduce(..., keepdims=True)
new_sizes = dict(zip(self.dims, variable.shape))
coords = {
k: v
for k, v in self._coords.items()
if v.shape == tuple(new_sizes[d] for d in v.dims)
}
indexes = filter_indexes_from_coords(self._indexes, set(coords))
else:
allowed_dims = set(variable.dims)
coords = {
k: v for k, v in self._coords.items() if set(v.dims) <= allowed_dims
}
indexes = filter_indexes_from_coords(self._indexes, set(coords))
return self._replace(variable, coords, name, indexes=indexes)
def _overwrite_indexes(
self: T_DataArray,
indexes: Mapping[Any, Index],
coords: Mapping[Any, Variable] = None,
drop_coords: list[Hashable] = None,
rename_dims: Mapping[Any, Any] = None,
) -> T_DataArray:
"""Maybe replace indexes and their corresponding coordinates."""
if not indexes:
return self
if coords is None:
coords = {}
if drop_coords is None:
drop_coords = []
new_variable = self.variable.copy()
new_coords = self._coords.copy()
new_indexes = dict(self._indexes)
for name in indexes:
new_coords[name] = coords[name]
new_indexes[name] = indexes[name]
for name in drop_coords:
new_coords.pop(name)
new_indexes.pop(name)
if rename_dims:
new_variable.dims = [rename_dims.get(d, d) for d in new_variable.dims]
return self._replace(
variable=new_variable, coords=new_coords, indexes=new_indexes
)
def _to_temp_dataset(self) -> Dataset:
return self._to_dataset_whole(name=_THIS_ARRAY, shallow_copy=False)
def _from_temp_dataset(
self: T_DataArray, dataset: Dataset, name: Hashable | None | Default = _default
) -> T_DataArray:
variable = dataset._variables.pop(_THIS_ARRAY)
coords = dataset._variables
indexes = dataset._indexes
return self._replace(variable, coords, name, indexes=indexes)
def _to_dataset_split(self, dim: Hashable) -> Dataset:
"""splits dataarray along dimension 'dim'"""
def subset(dim, label):
array = self.loc[{dim: label}]
array.attrs = {}
return as_variable(array)
variables = {label: subset(dim, label) for label in self.get_index(dim)}
variables.update({k: v for k, v in self._coords.items() if k != dim})
coord_names = set(self._coords) - {dim}
indexes = filter_indexes_from_coords(self._indexes, coord_names)
dataset = Dataset._construct_direct(
variables, coord_names, indexes=indexes, attrs=self.attrs
)
return dataset
def _to_dataset_whole(
self, name: Hashable = None, shallow_copy: bool = True
) -> Dataset:
if name is None:
name = self.name
if name is None:
raise ValueError(
"unable to convert unnamed DataArray to a "
"Dataset without providing an explicit name"
)
if name in self.coords:
raise ValueError(
"cannot create a Dataset from a DataArray with "
"the same name as one of its coordinates"
)
# use private APIs for speed: this is called by _to_temp_dataset(),
# which is used in the guts of a lot of operations (e.g., reindex)
variables = self._coords.copy()
variables[name] = self.variable
if shallow_copy:
for k in variables:
variables[k] = variables[k].copy(deep=False)
indexes = self._indexes
coord_names = set(self._coords)
return Dataset._construct_direct(variables, coord_names, indexes=indexes)
def to_dataset(
self,
dim: Hashable = None,
*,
name: Hashable = None,
promote_attrs: bool = False,
) -> Dataset:
"""Convert a DataArray to a Dataset.
Parameters
----------
dim : Hashable, optional
Name of the dimension on this array along which to split this array
into separate variables. If not provided, this array is converted
into a Dataset of one variable.
name : Hashable, optional
Name to substitute for this array's name. Only valid if ``dim`` is
not provided.
promote_attrs : bool, default: False
Set to True to shallow copy attrs of DataArray to returned Dataset.
Returns
-------
dataset : Dataset
"""
if dim is not None and dim not in self.dims:
raise TypeError(
f"{dim} is not a dim. If supplying a ``name``, pass as a kwarg."
)
if dim is not None:
if name is not None:
raise TypeError("cannot supply both dim and name arguments")
result = self._to_dataset_split(dim)
else:
result = self._to_dataset_whole(name)
if promote_attrs:
result.attrs = dict(self.attrs)
return result
@property
def name(self) -> Hashable | None:
"""The name of this array."""
return self._name
@name.setter
def name(self, value: Hashable | None) -> None:
self._name = value
@property
def variable(self) -> Variable:
"""Low level interface to the Variable object for this DataArray."""
return self._variable
@property
def dtype(self) -> np.dtype:
return self.variable.dtype
@property
def shape(self) -> tuple[int, ...]:
return self.variable.shape
@property
def size(self) -> int:
return self.variable.size
@property
def nbytes(self) -> int:
return self.variable.nbytes
@property
def ndim(self) -> int:
return self.variable.ndim
def __len__(self) -> int:
return len(self.variable)
@property
def data(self) -> Any:
"""
The DataArray's data as an array. The underlying array type
(e.g. dask, sparse, pint) is preserved.
See Also
--------
DataArray.to_numpy
DataArray.as_numpy
DataArray.values
"""
return self.variable.data
@data.setter
def data(self, value: Any) -> None:
self.variable.data = value
@property
def values(self) -> np.ndarray:
"""
The array's data as a numpy.ndarray.
If the array's data is not a numpy.ndarray this will attempt to convert
it naively using np.array(), which will raise an error if the array
type does not support coercion like this (e.g. cupy).
"""
return self.variable.values
@values.setter
def values(self, value: Any) -> None:
self.variable.values = value
def to_numpy(self) -> np.ndarray:
"""
Coerces wrapped data to numpy and returns a numpy.ndarray.
See Also
--------
DataArray.as_numpy : Same but returns the surrounding DataArray instead.
Dataset.as_numpy
DataArray.values
DataArray.data
"""
return self.variable.to_numpy()
def as_numpy(self: T_DataArray) -> T_DataArray:
"""
Coerces wrapped data and coordinates into numpy arrays, returning a DataArray.
See Also
--------
DataArray.to_numpy : Same but returns only the data as a numpy.ndarray object.
Dataset.as_numpy : Converts all variables in a Dataset.
DataArray.values
DataArray.data
"""
coords = {k: v.as_numpy() for k, v in self._coords.items()}
return self._replace(self.variable.as_numpy(), coords, indexes=self._indexes)
@property
def _in_memory(self) -> bool:
return self.variable._in_memory
def to_index(self) -> pd.Index:
"""Convert this variable to a pandas.Index. Only possible for 1D
arrays.
"""
return self.variable.to_index()
@property
def dims(self) -> tuple[Hashable, ...]:
"""Tuple of dimension names associated with this array.
Note that the type of this property is inconsistent with
`Dataset.dims`. See `Dataset.sizes` and `DataArray.sizes` for
consistently named properties.
See Also
--------
DataArray.sizes
Dataset.dims
"""
return self.variable.dims
@dims.setter
def dims(self, value: Any) -> NoReturn:
raise AttributeError(
"you cannot assign dims on a DataArray. Use "
".rename() or .swap_dims() instead."
)
def _item_key_to_dict(self, key: Any) -> Mapping[Hashable, Any]:
if utils.is_dict_like(key):
return key
key = indexing.expanded_indexer(key, self.ndim)
return dict(zip(self.dims, key))
def _getitem_coord(self: T_DataArray, key: Any) -> T_DataArray:
from .dataset import _get_virtual_variable
try:
var = self._coords[key]
except KeyError:
dim_sizes = dict(zip(self.dims, self.shape))
_, key, var = _get_virtual_variable(self._coords, key, dim_sizes)
return self._replace_maybe_drop_dims(var, name=key)
def __getitem__(self: T_DataArray, key: Any) -> T_DataArray:
if isinstance(key, str):
return self._getitem_coord(key)
else:
# xarray-style array indexing
return self.isel(indexers=self._item_key_to_dict(key))
def __setitem__(self, key: Any, value: Any) -> None:
if isinstance(key, str):
self.coords[key] = value
else:
# Coordinates in key, value and self[key] should be consistent.
# TODO Coordinate consistency in key is checked here, but it
# causes unnecessary indexing. It should be optimized.
obj = self[key]
if isinstance(value, DataArray):
assert_coordinate_consistent(value, obj.coords.variables)
# DataArray key -> Variable key
key = {
k: v.variable if isinstance(v, DataArray) else v
for k, v in self._item_key_to_dict(key).items()
}
self.variable[key] = value
def __delitem__(self, key: Any) -> None:
del self.coords[key]
@property
def _attr_sources(self) -> Iterable[Mapping[Hashable, Any]]:
"""Places to look-up items for attribute-style access"""
yield from self._item_sources
yield self.attrs
@property
def _item_sources(self) -> Iterable[Mapping[Hashable, Any]]:
"""Places to look-up items for key-completion"""
yield HybridMappingProxy(keys=self._coords, mapping=self.coords)
# virtual coordinates
# uses empty dict -- everything here can already be found in self.coords.
yield HybridMappingProxy(keys=self.dims, mapping={})
def __contains__(self, key: Any) -> bool:
return key in self.data
@property
def loc(self) -> _LocIndexer:
"""Attribute for location based indexing like pandas."""
return _LocIndexer(self)
@property
# Key type needs to be `Any` because of mypy#4167
def attrs(self) -> dict[Any, Any]:
"""Dictionary storing arbitrary metadata with this array."""
return self.variable.attrs
@attrs.setter
def attrs(self, value: Mapping[Any, Any]) -> None:
# Disable type checking to work around mypy bug - see mypy#4167
self.variable.attrs = value # type: ignore[assignment]
@property
def encoding(self) -> dict[Hashable, Any]:
"""Dictionary of format-specific settings for how this array should be
serialized."""
return self.variable.encoding
@encoding.setter
def encoding(self, value: Mapping[Any, Any]) -> None:
self.variable.encoding = value
@property
def indexes(self) -> Indexes:
"""Mapping of pandas.Index objects used for label based indexing.
Raises an error if this Dataset has indexes that cannot be coerced
to pandas.Index objects.
See Also
--------
DataArray.xindexes
"""
return self.xindexes.to_pandas_indexes()
@property
def xindexes(self) -> Indexes:
"""Mapping of xarray Index objects used for label based indexing."""
return Indexes(self._indexes, {k: self._coords[k] for k in self._indexes})
@property
def coords(self) -> DataArrayCoordinates:
"""Dictionary-like container of coordinate arrays."""
return DataArrayCoordinates(self)
@overload
def reset_coords(
self: T_DataArray,
names: Hashable | Iterable[Hashable] | None = None,
drop: Literal[False] = False,
) -> Dataset:
...
@overload
def reset_coords(
self: T_DataArray,
names: Hashable | Iterable[Hashable] | None = None,
*,
drop: Literal[True],
) -> T_DataArray:
...
def reset_coords(
self: T_DataArray,
names: Hashable | Iterable[Hashable] | None = None,
drop: bool = False,
) -> T_DataArray | Dataset:
"""Given names of coordinates, reset them to become variables.
Parameters
----------
names : Hashable or iterable of Hashable, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default, all non-index coordinates are reset.
drop : bool, default: False
If True, remove coordinates instead of converting them into
variables.
Returns
-------
Dataset, or DataArray if ``drop == True``
"""
if names is None:
names = set(self.coords) - set(self._indexes)
dataset = self.coords.to_dataset().reset_coords(names, drop)
if drop:
return self._replace(coords=dataset._variables)
if self.name is None:
raise ValueError(
"cannot reset_coords with drop=False on an unnamed DataArrray"
)
dataset[self.name] = self.variable
return dataset
def __dask_tokenize__(self):
from dask.base import normalize_token
return normalize_token((type(self), self._variable, self._coords, self._name))
def __dask_graph__(self):
return self._to_temp_dataset().__dask_graph__()
def __dask_keys__(self):
return self._to_temp_dataset().__dask_keys__()
def __dask_layers__(self):
return self._to_temp_dataset().__dask_layers__()
@property
def __dask_optimize__(self):
return self._to_temp_dataset().__dask_optimize__
@property
def __dask_scheduler__(self):
return self._to_temp_dataset().__dask_scheduler__
def __dask_postcompute__(self):
func, args = self._to_temp_dataset().__dask_postcompute__()
return self._dask_finalize, (self.name, func) + args
def __dask_postpersist__(self):
func, args = self._to_temp_dataset().__dask_postpersist__()
return self._dask_finalize, (self.name, func) + args
@staticmethod
def _dask_finalize(results, name, func, *args, **kwargs) -> DataArray:
ds = func(results, *args, **kwargs)
variable = ds._variables.pop(_THIS_ARRAY)
coords = ds._variables
indexes = ds._indexes
return DataArray(variable, coords, name=name, indexes=indexes, fastpath=True)
def load(self: T_DataArray, **kwargs) -> T_DataArray:
"""Manually trigger loading of this array's data from disk or a
remote source into memory and return this array.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically. However, this method can be necessary when
working with many file objects on disk.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.compute``.
See Also
--------
dask.compute
"""
ds = self._to_temp_dataset().load(**kwargs)
new = self._from_temp_dataset(ds)
self._variable = new._variable
self._coords = new._coords
return self
def compute(self: T_DataArray, **kwargs) -> T_DataArray:
"""Manually trigger loading of this array's data from disk or a
remote source into memory and return a new array. The original is
left unaltered.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically. However, this method can be necessary when
working with many file objects on disk.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.compute``.
See Also
--------
dask.compute
"""
new = self.copy(deep=False)
return new.load(**kwargs)
def persist(self: T_DataArray, **kwargs) -> T_DataArray:
"""Trigger computation in constituent dask arrays
This keeps them as dask arrays but encourages them to keep data in
memory. This is particularly useful when on a distributed machine.
When on a single machine consider using ``.compute()`` instead.