forked from pydata/xarray
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataarray.py
More file actions
2514 lines (2123 loc) · 90.1 KB
/
dataarray.py
File metadata and controls
2514 lines (2123 loc) · 90.1 KB
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
import functools
import sys
import warnings
from collections import OrderedDict
import numpy as np
import pandas as pd
from ..plot.plot import _PlotMethods
from . import (
computation, dtypes, groupby, indexing, ops, resample, rolling, utils)
from .accessors import DatetimeAccessor
from .alignment import align, reindex_like_indexers
from .common import AbstractArray, DataWithCoords
from .coordinates import (
DataArrayCoordinates, LevelCoordinatesSource, assert_coordinate_consistent,
remap_label_indexers)
from .dataset import Dataset, merge_indexes, split_indexes
from .formatting import format_item
from .indexes import Indexes, default_indexes
from .options import OPTIONS
from .utils import _check_inplace, either_dict_or_kwargs
from .variable import (
IndexVariable, Variable, as_compatible_data, as_variable,
assert_unique_multiindex_level_names)
def _infer_coords_and_dims(shape, coords, dims):
"""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('coords is not dict-like, but it has %s items, '
'which does not match the %s dimensions of the '
'data' % (len(coords), len(shape)))
if isinstance(dims, str):
dims = (dims,)
if dims is None:
dims = ['dim_%s' % 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):
# deprecated in GH993, removed in GH1539
raise ValueError('inferring DataArray dimensions from '
'dictionary like ``coords`` is no longer '
'supported. Use an explicit list of '
'``dims`` instead.')
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)
else:
for d in dims:
if not isinstance(d, str):
raise TypeError('dimension %s is not a string' % d)
new_coords = OrderedDict()
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
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('coordinate %s has dimensions %s, but these '
'are not a subset of the DataArray '
'dimensions %s' % (k, v.dims, dims))
for d, s in zip(v.dims, v.shape):
if s != sizes[d]:
raise ValueError('conflicting sizes for dimension %r: '
'length %s on the data but length %s on '
'coordinate %r' % (d, sizes[d], s, k))
if k in sizes and v.shape != (sizes[k],):
raise ValueError('coordinate %r is a DataArray dimension, but '
'it has shape %r rather than expected shape %r '
'matching the dimension size'
% (k, v.shape, (sizes[k],)))
assert_unique_multiindex_level_names(new_coords)
return new_coords, dims
class _LocIndexer(object):
def __init__(self, data_array):
self.data_array = data_array
def __getitem__(self, key):
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):
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))
pos_indexers, _ = remap_label_indexers(self.data_array, **key)
self.data_array[pos_indexers] = value
# Used as the key corresponding to a DataArray's variable when converting
# arbitrary DataArray objects to datasets
_THIS_ARRAY = utils.ReprObject('<this-array>')
class DataArray(AbstractArray, DataWithCoords):
"""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.
Attributes
----------
dims : tuple
Dimension names associated with this array.
values : np.ndarray
Access or modify DataArray values as a numpy array.
coords : dict-like
Dictionary of DataArray objects that label values along each dimension.
name : str or None
Name of this array.
attrs : OrderedDict
Dictionary for holding arbitrary metadata.
"""
_groupby_cls = groupby.DataArrayGroupBy
_rolling_cls = rolling.DataArrayRolling
_coarsen_cls = rolling.DataArrayCoarsen
_resample_cls = resample.DataArrayResample
dt = property(DatetimeAccessor)
def __init__(self, data, coords=None, dims=None, name=None,
attrs=None, encoding=None, indexes=None, fastpath=False):
"""
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 objects, optional
Coordinates (tick labels) to use for indexing along each dimension.
If dict-like, should be a mapping from dimension names to the
corresponding coordinates. If sequence-like, should be a sequence
of tuples where the first element is the dimension name and the
second element is the corresponding coordinate array_like object.
dims : str or sequence of str, optional
Name(s) of the data dimension(s). Must be either a string (only
for 1D data) or a sequence of strings 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.
encoding : deprecated
"""
if encoding is not None:
warnings.warn(
'The `encoding` argument to `DataArray` is deprecated, and . '
'will be removed in 0.13. '
'Instead, specify the encoding when writing to disk or '
'set the `encoding` attribute directly.',
FutureWarning, stacklevel=2)
if fastpath:
variable = data
assert dims is None
assert attrs is None
assert encoding is None
else:
# try to fill in arguments from data if they weren't supplied
if coords is None:
coords = getattr(data, 'coords', None)
if 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]
elif isinstance(data, pd.Panel):
coords = [data.items, data.major_axis, data.minor_axis]
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:
attrs = getattr(data, 'attrs', None)
if encoding is None:
encoding = getattr(data, 'encoding', None)
data = as_compatible_data(data)
coords, dims = _infer_coords_and_dims(data.shape, coords, dims)
variable = Variable(dims, data, attrs, encoding, fastpath=True)
# These fully describe a DataArray
self._variable = variable
self._coords = coords
self._name = name
# TODO(shoyer): document this argument, once it becomes part of the
# public interface.
self._indexes = indexes
self._file_obj = None
self._initialized = True
__default = object()
def _replace(self, variable=None, coords=None, name=__default):
if variable is None:
variable = self.variable
if coords is None:
coords = self._coords
if name is self.__default:
name = self.name
return type(self)(variable, coords, name=name, fastpath=True)
def _replace_maybe_drop_dims(self, variable, name=__default):
if variable.dims == self.dims:
coords = self._coords.copy()
else:
allowed_dims = set(variable.dims)
coords = OrderedDict((k, v) for k, v in self._coords.items()
if set(v.dims) <= allowed_dims)
return self._replace(variable, coords, name)
def _replace_indexes(self, indexes):
if not len(indexes):
return self
coords = self._coords.copy()
for name, idx in indexes.items():
coords[name] = IndexVariable(name, idx)
obj = self._replace(coords=coords)
# switch from dimension to level names, if necessary
dim_names = {}
for dim, idx in indexes.items():
if not isinstance(idx, pd.MultiIndex) and idx.name != dim:
dim_names[dim] = idx.name
if dim_names:
obj = obj.rename(dim_names)
return obj
def _to_temp_dataset(self):
return self._to_dataset_whole(name=_THIS_ARRAY,
shallow_copy=False)
def _from_temp_dataset(self, dataset, name=__default):
variable = dataset._variables.pop(_THIS_ARRAY)
coords = dataset._variables
return self._replace(variable, coords, name)
def _to_dataset_split(self, dim):
def subset(dim, label):
array = self.loc[{dim: label}]
if dim in array.coords:
del array.coords[dim]
array.attrs = {}
return array
variables = OrderedDict([(label, subset(dim, label))
for label in self.get_index(dim)])
coords = self.coords.to_dataset()
if dim in coords:
del coords[dim]
return Dataset(variables, coords, self.attrs)
def _to_dataset_whole(self, name=None, shallow_copy=True):
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)
coord_names = set(self._coords)
dataset = Dataset._from_vars_and_coord_names(variables, coord_names)
return dataset
def to_dataset(self, dim=None, name=None):
"""Convert a DataArray to a Dataset.
Parameters
----------
dim : str, 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 : str, optional
Name to substitute for this array's name. Only valid if ``dim`` is
not provided.
Returns
-------
dataset : Dataset
"""
if dim is not None and dim not in self.dims:
warnings.warn('the order of the arguments on DataArray.to_dataset '
'has changed; you now need to supply ``name`` as '
'a keyword argument',
FutureWarning, stacklevel=2)
name = dim
dim = None
if dim is not None:
if name is not None:
raise TypeError('cannot supply both dim and name arguments')
return self._to_dataset_split(dim)
else:
return self._to_dataset_whole(name)
@property
def name(self):
"""The name of this array.
"""
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def variable(self):
"""Low level interface to the Variable object for this DataArray."""
return self._variable
@property
def dtype(self):
return self.variable.dtype
@property
def shape(self):
return self.variable.shape
@property
def size(self):
return self.variable.size
@property
def nbytes(self):
return self.variable.nbytes
@property
def ndim(self):
return self.variable.ndim
def __len__(self):
return len(self.variable)
@property
def data(self):
"""The array's data as a dask or numpy array"""
return self.variable.data
@data.setter
def data(self, value):
self.variable.data = value
@property
def values(self):
"""The array's data as a numpy.ndarray"""
return self.variable.values
@values.setter
def values(self, value):
self.variable.values = value
@property
def _in_memory(self):
return self.variable._in_memory
def to_index(self):
"""Convert this variable to a pandas.Index. Only possible for 1D
arrays.
"""
return self.variable.to_index()
@property
def dims(self):
"""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.
"""
return self.variable.dims
@dims.setter
def dims(self, value):
raise AttributeError('you cannot assign dims on a DataArray. Use '
'.rename() or .swap_dims() instead.')
def _item_key_to_dict(self, key):
if utils.is_dict_like(key):
return key
else:
key = indexing.expanded_indexer(key, self.ndim)
return dict(zip(self.dims, key))
@property
def _level_coords(self):
"""Return a mapping of all MultiIndex levels and their corresponding
coordinate name.
"""
level_coords = OrderedDict()
for cname, var in self._coords.items():
if var.ndim == 1 and isinstance(var, IndexVariable):
level_names = var.level_names
if level_names is not None:
dim, = var.dims
level_coords.update({lname: dim for lname in level_names})
return level_coords
def _getitem_coord(self, key):
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, self._level_coords, dim_sizes)
return self._replace_maybe_drop_dims(var, name=key)
def __getitem__(self, key):
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, value):
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):
del self.coords[key]
@property
def _attr_sources(self):
"""List of places to look-up items for attribute-style access"""
return self._item_sources + [self.attrs]
@property
def _item_sources(self):
"""List of places to look-up items for key-completion"""
return [self.coords, {d: self.coords[d] for d in self.dims},
LevelCoordinatesSource(self)]
def __contains__(self, key):
return key in self.data
@property
def loc(self):
"""Attribute for location based indexing like pandas.
"""
return _LocIndexer(self)
@property
def attrs(self):
"""Dictionary storing arbitrary metadata with this array."""
return self.variable.attrs
@attrs.setter
def attrs(self, value):
self.variable.attrs = value
@property
def encoding(self):
"""Dictionary of format-specific settings for how this array should be
serialized."""
return self.variable.encoding
@encoding.setter
def encoding(self, value):
self.variable.encoding = value
@property
def indexes(self):
"""Mapping of pandas.Index objects used for label based indexing
"""
if self._indexes is None:
self._indexes = default_indexes(self._coords, self.dims)
return Indexes(self._indexes)
@property
def coords(self):
"""Dictionary-like container of coordinate arrays.
"""
return DataArrayCoordinates(self)
def reset_coords(self, names=None, drop=False, inplace=None):
"""Given names of coordinates, reset them to become variables.
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default, all non-index coordinates are reset.
drop : bool, optional
If True, remove coordinates instead of converting them into
variables.
inplace : bool, optional
If True, modify this dataset inplace. Otherwise, create a new
object.
Returns
-------
Dataset, or DataArray if ``drop == True``
"""
inplace = _check_inplace(inplace)
if inplace and not drop:
raise ValueError('cannot reset coordinates in-place on a '
'DataArray without ``drop == True``')
if names is None:
names = set(self.coords) - set(self.dims)
dataset = self.coords.to_dataset().reset_coords(names, drop)
if drop:
if inplace:
self._coords = dataset._variables
else:
return self._replace(coords=dataset._variables)
else:
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_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, (func, args, self.name)
def __dask_postpersist__(self):
func, args = self._to_temp_dataset().__dask_postpersist__()
return self._dask_finalize, (func, args, self.name)
@staticmethod
def _dask_finalize(results, func, args, name):
ds = func(results, *args)
variable = ds._variables.pop(_THIS_ARRAY)
coords = ds._variables
return DataArray(variable, coords, name=name, fastpath=True)
def load(self, **kwargs):
"""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.array.compute``.
See Also
--------
dask.array.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, **kwargs):
"""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.array.compute``.
See Also
--------
dask.array.compute
"""
new = self.copy(deep=False)
return new.load(**kwargs)
def persist(self, **kwargs):
""" 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.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.persist``.
See Also
--------
dask.persist
"""
ds = self._to_temp_dataset().persist(**kwargs)
return self._from_temp_dataset(ds)
def copy(self, deep=True, data=None):
"""Returns a copy of this array.
If `deep=True`, a deep copy is made of the data array.
Otherwise, a shallow copy is made, so each variable in the new
array's dataset is also a variable in this array's dataset.
Use `data` to create a new object with the same structure as
original but entirely new data.
Parameters
----------
deep : bool, optional
Whether the data array and its coordinates are loaded into memory
and copied onto the new object. Default is True.
data : array_like, optional
Data to use in the new object. Must have same shape as original.
When `data` is used, `deep` is ignored for all data variables,
and only used for coords.
Returns
-------
object : DataArray
New object with dimensions, attributes, coordinates, name,
encoding, and optionally data copied from original.
Examples
--------
Shallow versus deep copy
>>> array = xr.DataArray([1, 2, 3], dims='x',
... coords={'x': ['a', 'b', 'c']})
>>> array.copy()
<xarray.DataArray (x: 3)>
array([1, 2, 3])
Coordinates:
* x (x) <U1 'a' 'b' 'c'
>>> array_0 = array.copy(deep=False)
>>> array_0[0] = 7
>>> array_0
<xarray.DataArray (x: 3)>
array([7, 2, 3])
Coordinates:
* x (x) <U1 'a' 'b' 'c'
>>> array
<xarray.DataArray (x: 3)>
array([7, 2, 3])
Coordinates:
* x (x) <U1 'a' 'b' 'c'
Changing the data using the ``data`` argument maintains the
structure of the original object, but with the new data. Original
object is unaffected.
>>> array.copy(data=[0.1, 0.2, 0.3])
<xarray.DataArray (x: 3)>
array([ 0.1, 0.2, 0.3])
Coordinates:
* x (x) <U1 'a' 'b' 'c'
>>> array
<xarray.DataArray (x: 3)>
array([1, 2, 3])
Coordinates:
* x (x) <U1 'a' 'b' 'c'
See also
--------
pandas.DataFrame.copy
"""
variable = self.variable.copy(deep=deep, data=data)
coords = OrderedDict((k, v.copy(deep=deep))
for k, v in self._coords.items())
return self._replace(variable, coords)
def __copy__(self):
return self.copy(deep=False)
def __deepcopy__(self, memo=None):
# memo does nothing but is required for compatibility with
# copy.deepcopy
return self.copy(deep=True)
# mutable objects should not be hashable
# https://github.com/python/mypy/issues/4266
__hash__ = None # type: ignore
@property
def chunks(self):
"""Block dimensions for this array's data or None if it's not a dask
array.
"""
return self.variable.chunks
def chunk(self, chunks=None, name_prefix='xarray-', token=None,
lock=False):
"""Coerce this array's data into a dask arrays with the given chunks.
If this variable is a non-dask array, it will be converted to dask
array. If it's a dask array, it will be rechunked to the given chunk
sizes.
If neither chunks is not provided for one or more dimensions, chunk
sizes along that dimension will not be updated; non-dask arrays will be
converted into dask arrays with a single block.
Parameters
----------
chunks : int, tuple or dict, optional
Chunk sizes along each dimension, e.g., ``5``, ``(5, 5)`` or
``{'x': 5, 'y': 5}``.
name_prefix : str, optional
Prefix for the name of the new dask array.
token : str, optional
Token uniquely identifying this array.
lock : optional
Passed on to :py:func:`dask.array.from_array`, if the array is not
already as dask array.
Returns
-------
chunked : xarray.DataArray
"""
if isinstance(chunks, (list, tuple)):
chunks = dict(zip(self.dims, chunks))
ds = self._to_temp_dataset().chunk(chunks, name_prefix=name_prefix,
token=token, lock=lock)
return self._from_temp_dataset(ds)
def isel(self, indexers=None, drop=False, **indexers_kwargs):
"""Return a new DataArray whose dataset is given by integer indexing
along the specified dimension(s).
See Also
--------
Dataset.isel
DataArray.sel
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, 'isel')
ds = self._to_temp_dataset().isel(drop=drop, indexers=indexers)
return self._from_temp_dataset(ds)
def sel(self, indexers=None, method=None, tolerance=None, drop=False,
**indexers_kwargs):
"""Return a new DataArray whose dataset is given by selecting
index labels along the specified dimension(s).
.. warning::
Do not try to assign values when using any of the indexing methods
``isel`` or ``sel``::
da = xr.DataArray([0, 1, 2, 3], dims=['x'])
# DO NOT do this
da.isel(x=[0, 1, 2])[1] = -1
Assigning values with the chained indexing using ``.sel`` or
``.isel`` fails silently.
See Also
--------
Dataset.sel
DataArray.isel
"""
ds = self._to_temp_dataset().sel(
indexers=indexers, drop=drop, method=method, tolerance=tolerance,
**indexers_kwargs)
return self._from_temp_dataset(ds)
def isel_points(self, dim='points', **indexers):
"""Return a new DataArray whose dataset is given by pointwise integer
indexing along the specified dimension(s).
See Also
--------
Dataset.isel_points
"""
ds = self._to_temp_dataset().isel_points(dim=dim, **indexers)
return self._from_temp_dataset(ds)
def sel_points(self, dim='points', method=None, tolerance=None,
**indexers):
"""Return a new DataArray whose dataset is given by pointwise selection
of index labels along the specified dimension(s).
See Also
--------
Dataset.sel_points
"""
ds = self._to_temp_dataset().sel_points(
dim=dim, method=method, tolerance=tolerance, **indexers)
return self._from_temp_dataset(ds)
def reindex_like(self, other, method=None, tolerance=None, copy=True):
"""Conform this object onto the indexes of another object, filling
in missing values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to pandas.Index objects, which provides coordinates upon
which to index the variables in this dataset. The indexes on this
other object need not be the same as the indexes on this
dataset. Any mis-matched index values will be filled in with
NaN, and any mis-matched dimension names will simply be ignored.
method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
Method to use for filling index values from other not found on this
data array:
* None (default): don't fill gaps
* pad / ffill: propagate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value (requires pandas>=0.16)
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
Requires pandas>=0.17.
copy : bool, optional
If ``copy=True``, data in the return value is always copied. If
``copy=False`` and reindexing is unnecessary, or can be performed
with only slice operations, then the output may share memory with
the input. In either case, a new xarray object is always returned.
Returns
-------
reindexed : DataArray
Another dataset array, with this array's data but coordinates from
the other object.
See Also
--------
DataArray.reindex
align
"""
indexers = reindex_like_indexers(self, other)
return self.reindex(method=method, tolerance=tolerance, copy=copy,
**indexers)
def reindex(self, indexers=None, method=None, tolerance=None, copy=True,
**indexers_kwargs):
"""Conform this object onto a new set of indexes, filling in
missing values with NaN.
Parameters
----------
indexers : dict, optional
Dictionary with keys given by dimension names and values given by
arrays of coordinates tick labels. Any mis-matched coordinate
values will be filled in with NaN, and any mis-matched dimension
names will simply be ignored.
One of indexers or indexers_kwargs must be provided.
copy : bool, optional
If ``copy=True``, data in the return value is always copied. If
``copy=False`` and reindexing is unnecessary, or can be performed
with only slice operations, then the output may share memory with
the input. In either case, a new xarray object is always returned.
method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
Method to use for filling index values in ``indexers`` not found on
this data array:
* None (default): don't fill gaps
* pad / ffill: propagate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value (requires pandas>=0.16)
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
**indexers_kwarg : {dim: indexer, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
Returns
-------
reindexed : DataArray
Another dataset array, with this array's data but replaced
coordinates.
See Also
--------
DataArray.reindex_like
align
"""
indexers = either_dict_or_kwargs(
indexers, indexers_kwargs, 'reindex')
ds = self._to_temp_dataset().reindex(
indexers=indexers, method=method, tolerance=tolerance, copy=copy)
return self._from_temp_dataset(ds)
def interp(self, coords=None, method='linear', assume_sorted=False,
kwargs={}, **coords_kwargs):
""" Multidimensional interpolation of variables.
coords : dict, optional
Mapping from dimension names to the new coordinates.
new coordinate can be an scalar, array-like or DataArray.
If DataArrays are passed as new coordates, their dimensions are
used for the broadcasting.
method: {'linear', 'nearest'} for multidimensional array,
{'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'}
for 1-dimensional array.
assume_sorted: boolean, optional
If False, values of x can be in any order and they are sorted
first. If True, x has to be an array of monotonically increasing
values.
kwargs: dictionary
Additional keyword passed to scipy's interpolator.
**coords_kwarg : {dim: coordinate, ...}, optional
The keyword arguments form of ``coords``.
One of coords or coords_kwargs must be provided.