85
85
either_dict_or_kwargs ,
86
86
hashable ,
87
87
is_dict_like ,
88
- is_list_like ,
89
88
is_scalar ,
90
89
maybe_wrap_array ,
91
90
)
92
- from .variable import IndexVariable , Variable , as_variable , broadcast_variables
91
+ from .variable import (
92
+ IndexVariable ,
93
+ Variable ,
94
+ as_variable ,
95
+ broadcast_variables ,
96
+ assert_unique_multiindex_level_names ,
97
+ )
93
98
94
99
if TYPE_CHECKING :
95
100
from ..backends import AbstractDataStore , ZarrStore
@@ -1748,7 +1753,10 @@ def maybe_chunk(name, var, chunks):
1748
1753
if not chunks :
1749
1754
chunks = None
1750
1755
if var .ndim > 0 :
1751
- token2 = tokenize (name , token if token else var ._data )
1756
+ # when rechunking by different amounts, make sure dask names change
1757
+ # by provinding chunks as an input to tokenize.
1758
+ # subtle bugs result otherwise. see GH3350
1759
+ token2 = tokenize (name , token if token else var ._data , chunks )
1752
1760
name2 = f"{ name_prefix } { name } -{ token2 } "
1753
1761
return var .chunk (chunks , name = name2 , lock = lock )
1754
1762
else :
@@ -2780,6 +2788,7 @@ def rename(
2780
2788
variables , coord_names , dims , indexes = self ._rename_all (
2781
2789
name_dict = name_dict , dims_dict = name_dict
2782
2790
)
2791
+ assert_unique_multiindex_level_names (variables )
2783
2792
return self ._replace (variables , coord_names , dims = dims , indexes = indexes )
2784
2793
2785
2794
def rename_dims (
@@ -2791,7 +2800,8 @@ def rename_dims(
2791
2800
----------
2792
2801
dims_dict : dict-like, optional
2793
2802
Dictionary whose keys are current dimension names and
2794
- whose values are the desired names.
2803
+ whose values are the desired names. The desired names must
2804
+ not be the name of an existing dimension or Variable in the Dataset.
2795
2805
**dims, optional
2796
2806
Keyword form of ``dims_dict``.
2797
2807
One of dims_dict or dims must be provided.
@@ -2809,12 +2819,17 @@ def rename_dims(
2809
2819
DataArray.rename
2810
2820
"""
2811
2821
dims_dict = either_dict_or_kwargs (dims_dict , dims , "rename_dims" )
2812
- for k in dims_dict :
2822
+ for k , v in dims_dict . items () :
2813
2823
if k not in self .dims :
2814
2824
raise ValueError (
2815
2825
"cannot rename %r because it is not a "
2816
2826
"dimension in this dataset" % k
2817
2827
)
2828
+ if v in self .dims or v in self :
2829
+ raise ValueError (
2830
+ f"Cannot rename { k } to { v } because { v } already exists. "
2831
+ "Try using swap_dims instead."
2832
+ )
2818
2833
2819
2834
variables , coord_names , sizes , indexes = self ._rename_all (
2820
2835
name_dict = {}, dims_dict = dims_dict
@@ -2868,8 +2883,7 @@ def swap_dims(
2868
2883
----------
2869
2884
dims_dict : dict-like
2870
2885
Dictionary whose keys are current dimension names and whose values
2871
- are new names. Each value must already be a variable in the
2872
- dataset.
2886
+ are new names.
2873
2887
2874
2888
Returns
2875
2889
-------
@@ -2898,6 +2912,16 @@ def swap_dims(
2898
2912
Data variables:
2899
2913
a (y) int64 5 7
2900
2914
b (y) float64 0.1 2.4
2915
+ >>> ds.swap_dims({"x": "z"})
2916
+ <xarray.Dataset>
2917
+ Dimensions: (z: 2)
2918
+ Coordinates:
2919
+ x (z) <U1 'a' 'b'
2920
+ y (z) int64 0 1
2921
+ Dimensions without coordinates: z
2922
+ Data variables:
2923
+ a (z) int64 5 7
2924
+ b (z) float64 0.1 2.4
2901
2925
2902
2926
See Also
2903
2927
--------
@@ -2914,7 +2938,7 @@ def swap_dims(
2914
2938
"cannot swap from dimension %r because it is "
2915
2939
"not an existing dimension" % k
2916
2940
)
2917
- if self .variables [v ].dims != (k ,):
2941
+ if v in self . variables and self .variables [v ].dims != (k ,):
2918
2942
raise ValueError (
2919
2943
"replacement dimension %r is not a 1D "
2920
2944
"variable along the old dimension %r" % (v , k )
@@ -2923,7 +2947,7 @@ def swap_dims(
2923
2947
result_dims = {dims_dict .get (dim , dim ) for dim in self .dims }
2924
2948
2925
2949
coord_names = self ._coord_names .copy ()
2926
- coord_names .update (dims_dict .values ())
2950
+ coord_names .update ({ dim for dim in dims_dict .values () if dim in self . variables } )
2927
2951
2928
2952
variables : Dict [Hashable , Variable ] = {}
2929
2953
indexes : Dict [Hashable , pd .Index ] = {}
@@ -3525,7 +3549,7 @@ def update(self, other: "CoercibleMapping", inplace: bool = None) -> "Dataset":
3525
3549
3526
3550
def merge (
3527
3551
self ,
3528
- other : "CoercibleMapping" ,
3552
+ other : Union [ "CoercibleMapping" , "DataArray" ] ,
3529
3553
inplace : bool = None ,
3530
3554
overwrite_vars : Union [Hashable , Iterable [Hashable ]] = frozenset (),
3531
3555
compat : str = "no_conflicts" ,
@@ -3582,6 +3606,7 @@ def merge(
3582
3606
If any variables conflict (see ``compat``).
3583
3607
"""
3584
3608
_check_inplace (inplace )
3609
+ other = other .to_dataset () if isinstance (other , xr .DataArray ) else other
3585
3610
merge_result = dataset_merge_method (
3586
3611
self ,
3587
3612
other ,
@@ -3664,7 +3689,7 @@ def drop(self, labels=None, dim=None, *, errors="raise", **labels_kwargs):
3664
3689
raise ValueError ("cannot specify dim and dict-like arguments." )
3665
3690
labels = either_dict_or_kwargs (labels , labels_kwargs , "drop" )
3666
3691
3667
- if dim is None and (is_list_like (labels ) or is_scalar (labels )):
3692
+ if dim is None and (is_scalar (labels ) or isinstance (labels , Iterable )):
3668
3693
warnings .warn (
3669
3694
"dropping variables using `drop` will be deprecated; using drop_vars is encouraged." ,
3670
3695
PendingDeprecationWarning ,
@@ -4127,7 +4152,7 @@ def combine_first(self, other: "Dataset") -> "Dataset":
4127
4152
4128
4153
Returns
4129
4154
-------
4130
- DataArray
4155
+ Dataset
4131
4156
"""
4132
4157
out = ops .fillna (self , other , join = "outer" , dataset_join = "outer" )
4133
4158
return out
@@ -4641,7 +4666,7 @@ def to_dict(self, data=True):
4641
4666
conventions.
4642
4667
4643
4668
Converts all variables and attributes to native Python objects
4644
- Useful for coverting to json. To avoid datetime incompatibility
4669
+ Useful for converting to json. To avoid datetime incompatibility
4645
4670
use decode_times=False kwarg in xarrray.open_dataset.
4646
4671
4647
4672
Parameters
0 commit comments