Skip to content

Commit 620b946

Browse files
authored
Fix test failures / warnings for pandas 0.24 (#2720)
* Fix test failures / warnings for pandas 0.24 Fixes GH2717 * Brief doc note * Comment on name order
1 parent 882deac commit 620b946

File tree

6 files changed

+48
-42
lines changed

6 files changed

+48
-42
lines changed

doc/whats-new.rst

+2
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ Enhancements
4747
Bug fixes
4848
~~~~~~~~~
4949

50+
- Silenced warnings that appear when using pandas 0.24.
51+
By `Stephan Hoyer <https://github.com/shoyer>`_
5052
- Interpolating via resample now internally specifies ``bounds_error=False``
5153
as an argument to ``scipy.interpolate.interp1d``, allowing for interpolation
5254
from higher frequencies to lower frequencies. Datapoints outside the bounds

xarray/core/coordinates.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from collections import Mapping, OrderedDict
1+
import collections.abc
2+
from collections import OrderedDict
23
from contextlib import contextmanager
34

45
import pandas as pd
@@ -14,7 +15,7 @@
1415
_THIS_ARRAY = ReprObject('<this-array>')
1516

1617

17-
class AbstractCoordinates(Mapping):
18+
class AbstractCoordinates(collections.abc.Mapping):
1819
def __getitem__(self, key):
1920
raise NotImplementedError
2021

xarray/core/dataset.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ def merge_indexes(
130130
if isinstance(var_names, str):
131131
var_names = [var_names]
132132

133-
names, labels, levels = [], [], [] # type: (list, list, list)
133+
names, codes, levels = [], [], [] # type: (list, list, list)
134134
current_index_variable = variables.get(dim)
135135

136136
for n in var_names:
@@ -144,13 +144,18 @@ def merge_indexes(
144144
if current_index_variable is not None and append:
145145
current_index = current_index_variable.to_index()
146146
if isinstance(current_index, pd.MultiIndex):
147+
try:
148+
current_codes = current_index.codes
149+
except AttributeError:
150+
# fpr pandas<0.24
151+
current_codes = current_index.labels
147152
names.extend(current_index.names)
148-
labels.extend(current_index.labels)
153+
codes.extend(current_codes)
149154
levels.extend(current_index.levels)
150155
else:
151156
names.append('%s_level_0' % dim)
152157
cat = pd.Categorical(current_index.values, ordered=True)
153-
labels.append(cat.codes)
158+
codes.append(cat.codes)
154159
levels.append(cat.categories)
155160

156161
if not len(names) and len(var_names) == 1:
@@ -161,10 +166,10 @@ def merge_indexes(
161166
names.append(n)
162167
var = variables[n]
163168
cat = pd.Categorical(var.values, ordered=True)
164-
labels.append(cat.codes)
169+
codes.append(cat.codes)
165170
levels.append(cat.categories)
166171

167-
idx = pd.MultiIndex(labels=labels, levels=levels, names=names)
172+
idx = pd.MultiIndex(levels, codes, names=names)
168173

169174
vars_to_replace[dim] = IndexVariable(dim, idx)
170175
vars_to_remove.extend(var_names)

xarray/tests/test_coding_times.py

+15-10
Original file line numberDiff line numberDiff line change
@@ -533,17 +533,22 @@ def test_infer_cftime_datetime_units(calendar, date_args, expected):
533533

534534
@pytest.mark.parametrize(
535535
['timedeltas', 'units', 'numbers'],
536-
[('1D', 'days', np.int64(1)),
537-
(['1D', '2D', '3D'], 'days', np.array([1, 2, 3], 'int64')),
538-
('1h', 'hours', np.int64(1)),
539-
('1ms', 'milliseconds', np.int64(1)),
540-
('1us', 'microseconds', np.int64(1)),
541-
(['NaT', '0s', '1s'], None, [np.nan, 0, 1]),
542-
(['30m', '60m'], 'hours', [0.5, 1.0]),
543-
(np.timedelta64('NaT', 'ns'), 'days', np.nan),
544-
(['NaT', 'NaT'], 'days', [np.nan, np.nan])])
536+
[
537+
('1D', 'days', np.int64(1)),
538+
(['1D', '2D', '3D'], 'days', np.array([1, 2, 3], 'int64')),
539+
('1h', 'hours', np.int64(1)),
540+
('1ms', 'milliseconds', np.int64(1)),
541+
('1us', 'microseconds', np.int64(1)),
542+
(['NaT', '0s', '1s'], None, [np.nan, 0, 1]),
543+
(['30m', '60m'], 'hours', [0.5, 1.0]),
544+
('NaT', 'days', np.nan),
545+
(['NaT', 'NaT'], 'days', [np.nan, np.nan]),
546+
])
545547
def test_cf_timedelta(timedeltas, units, numbers):
546-
timedeltas = pd.to_timedelta(timedeltas, box=False)
548+
if timedeltas == 'NaT':
549+
timedeltas = np.timedelta64('NaT', 'ns')
550+
else:
551+
timedeltas = pd.to_timedelta(timedeltas, box=False)
547552
numbers = np.array(numbers)
548553

549554
expected = numbers

xarray/tests/test_dataarray.py

+12-23
Original file line numberDiff line numberDiff line change
@@ -122,21 +122,14 @@ def test_struct_array_dims(self):
122122
"""
123123
# GH837, GH861
124124
# checking array subraction when dims are the same
125-
p_data = np.array([('John', 180), ('Stacy', 150), ('Dick', 200)],
125+
# note: names need to be in sorted order to align consistently with
126+
# pandas < 0.24 and >= 0.24.
127+
p_data = np.array([('Abe', 180), ('Stacy', 150), ('Dick', 200)],
126128
dtype=[('name', '|S256'), ('height', object)])
127-
128-
p_data_1 = np.array([('John', 180), ('Stacy', 150), ('Dick', 200)],
129-
dtype=[('name', '|S256'), ('height', object)])
130-
131-
p_data_2 = np.array([('John', 180), ('Dick', 200)],
132-
dtype=[('name', '|S256'), ('height', object)])
133-
134129
weights_0 = DataArray([80, 56, 120], dims=['participant'],
135130
coords={'participant': p_data})
136-
137131
weights_1 = DataArray([81, 52, 115], dims=['participant'],
138-
coords={'participant': p_data_1})
139-
132+
coords={'participant': p_data})
140133
actual = weights_1 - weights_0
141134

142135
expected = DataArray([1, -4, -5], dims=['participant'],
@@ -145,31 +138,27 @@ def test_struct_array_dims(self):
145138
assert_identical(actual, expected)
146139

147140
# checking array subraction when dims are not the same
148-
p_data_1 = np.array([('John', 180), ('Stacy', 151), ('Dick', 200)],
149-
dtype=[('name', '|S256'), ('height', object)])
150-
141+
p_data_alt = np.array([('Abe', 180), ('Stacy', 151), ('Dick', 200)],
142+
dtype=[('name', '|S256'), ('height', object)])
151143
weights_1 = DataArray([81, 52, 115], dims=['participant'],
152-
coords={'participant': p_data_1})
153-
144+
coords={'participant': p_data_alt})
154145
actual = weights_1 - weights_0
155146

156147
expected = DataArray([1, -5], dims=['participant'],
157-
coords={'participant': p_data_2})
148+
coords={'participant': p_data[[0, 2]]})
158149

159150
assert_identical(actual, expected)
160151

161152
# checking array subraction when dims are not the same and one
162153
# is np.nan
163-
p_data_1 = np.array([('John', 180), ('Stacy', np.nan), ('Dick', 200)],
164-
dtype=[('name', '|S256'), ('height', object)])
165-
154+
p_data_nan = np.array([('Abe', 180), ('Stacy', np.nan), ('Dick', 200)],
155+
dtype=[('name', '|S256'), ('height', object)])
166156
weights_1 = DataArray([81, 52, 115], dims=['participant'],
167-
coords={'participant': p_data_1})
168-
157+
coords={'participant': p_data_nan})
169158
actual = weights_1 - weights_0
170159

171160
expected = DataArray([1, -5], dims=['participant'],
172-
coords={'participant': p_data_2})
161+
coords={'participant': p_data[[0, 2]]})
173162

174163
assert_identical(actual, expected)
175164

xarray/tests/test_utils.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ def test_multiindex_from_product_levels():
7474
result = utils.multiindex_from_product_levels(
7575
[pd.Index(['b', 'a']), pd.Index([1, 3, 2])])
7676
np.testing.assert_array_equal(
77-
result.labels, [[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])
77+
# compat for pandas < 0.24
78+
result.codes if hasattr(result, 'codes') else result.labels,
79+
[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])
7880
np.testing.assert_array_equal(result.levels[0], ['b', 'a'])
7981
np.testing.assert_array_equal(result.levels[1], [1, 3, 2])
8082

@@ -86,7 +88,9 @@ def test_multiindex_from_product_levels_non_unique():
8688
result = utils.multiindex_from_product_levels(
8789
[pd.Index(['b', 'a']), pd.Index([1, 1, 2])])
8890
np.testing.assert_array_equal(
89-
result.labels, [[0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1]])
91+
# compat for pandas < 0.24
92+
result.codes if hasattr(result, 'codes') else result.labels,
93+
[[0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1]])
9094
np.testing.assert_array_equal(result.levels[0], ['b', 'a'])
9195
np.testing.assert_array_equal(result.levels[1], [1, 2])
9296

0 commit comments

Comments
 (0)