Skip to content

Commit ec7f628

Browse files
authored
fix da.pad example for numpy 1.20 (#4865)
1 parent 110c857 commit ec7f628

File tree

2 files changed

+31
-12
lines changed

2 files changed

+31
-12
lines changed

xarray/core/dataarray.py

+11-12
Original file line numberDiff line numberDiff line change
@@ -3851,9 +3851,8 @@ def pad(
38513851
38523852
Notes
38533853
-----
3854-
By default when ``mode="constant"`` and ``constant_values=None``, integer types will be
3855-
promoted to ``float`` and padded with ``np.nan``. To avoid type promotion
3856-
specify ``constant_values=np.nan``
3854+
For ``mode="constant"`` and ``constant_values=None``, integer types will be
3855+
promoted to ``float`` and padded with ``np.nan``.
38573856
38583857
Examples
38593858
--------
@@ -3880,16 +3879,16 @@ def pad(
38803879
* x (x) float64 nan 0.0 1.0 nan
38813880
* y (y) int64 10 20 30 40
38823881
z (x) float64 nan 100.0 200.0 nan
3883-
>>> da.pad(x=1, constant_values=np.nan)
3882+
3883+
Careful, ``constant_values`` are coerced to the data type of the array which may
3884+
lead to a loss of precision:
3885+
3886+
>>> da.pad(x=1, constant_values=1.23456789)
38843887
<xarray.DataArray (x: 4, y: 4)>
3885-
array([[-9223372036854775808, -9223372036854775808, -9223372036854775808,
3886-
-9223372036854775808],
3887-
[ 0, 1, 2,
3888-
3],
3889-
[ 10, 11, 12,
3890-
13],
3891-
[-9223372036854775808, -9223372036854775808, -9223372036854775808,
3892-
-9223372036854775808]])
3888+
array([[ 1, 1, 1, 1],
3889+
[ 0, 1, 2, 3],
3890+
[10, 11, 12, 13],
3891+
[ 1, 1, 1, 1]])
38933892
Coordinates:
38943893
* x (x) float64 nan 0.0 1.0 nan
38953894
* y (y) int64 10 20 30 40

xarray/tests/test_dataarray.py

+20
Original file line numberDiff line numberDiff line change
@@ -4472,6 +4472,26 @@ def test_pad_constant(self):
44724472
assert actual.shape == (7, 4, 5)
44734473
assert_identical(actual, expected)
44744474

4475+
ar = xr.DataArray([9], dims="x")
4476+
4477+
actual = ar.pad(x=1)
4478+
expected = xr.DataArray([np.NaN, 9, np.NaN], dims="x")
4479+
assert_identical(actual, expected)
4480+
4481+
actual = ar.pad(x=1, constant_values=1.23456)
4482+
expected = xr.DataArray([1, 9, 1], dims="x")
4483+
assert_identical(actual, expected)
4484+
4485+
if LooseVersion(np.__version__) >= "1.20":
4486+
with pytest.raises(ValueError, match="cannot convert float NaN to integer"):
4487+
ar.pad(x=1, constant_values=np.NaN)
4488+
else:
4489+
actual = ar.pad(x=1, constant_values=np.NaN)
4490+
expected = xr.DataArray(
4491+
[-9223372036854775808, 9, -9223372036854775808], dims="x"
4492+
)
4493+
assert_identical(actual, expected)
4494+
44754495
def test_pad_coords(self):
44764496
ar = DataArray(
44774497
np.arange(3 * 4 * 5).reshape(3, 4, 5),

0 commit comments

Comments
 (0)