Skip to content

Commit

Permalink
fix da.pad example for numpy 1.20 (#4865)
Browse files Browse the repository at this point in the history
  • Loading branch information
mathause authored Feb 7, 2021
1 parent 110c857 commit ec7f628
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
23 changes: 11 additions & 12 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -3851,9 +3851,8 @@ def pad(
Notes
-----
By default when ``mode="constant"`` and ``constant_values=None``, integer types will be
promoted to ``float`` and padded with ``np.nan``. To avoid type promotion
specify ``constant_values=np.nan``
For ``mode="constant"`` and ``constant_values=None``, integer types will be
promoted to ``float`` and padded with ``np.nan``.
Examples
--------
Expand All @@ -3880,16 +3879,16 @@ def pad(
* x (x) float64 nan 0.0 1.0 nan
* y (y) int64 10 20 30 40
z (x) float64 nan 100.0 200.0 nan
>>> da.pad(x=1, constant_values=np.nan)
Careful, ``constant_values`` are coerced to the data type of the array which may
lead to a loss of precision:
>>> da.pad(x=1, constant_values=1.23456789)
<xarray.DataArray (x: 4, y: 4)>
array([[-9223372036854775808, -9223372036854775808, -9223372036854775808,
-9223372036854775808],
[ 0, 1, 2,
3],
[ 10, 11, 12,
13],
[-9223372036854775808, -9223372036854775808, -9223372036854775808,
-9223372036854775808]])
array([[ 1, 1, 1, 1],
[ 0, 1, 2, 3],
[10, 11, 12, 13],
[ 1, 1, 1, 1]])
Coordinates:
* x (x) float64 nan 0.0 1.0 nan
* y (y) int64 10 20 30 40
Expand Down
20 changes: 20 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4472,6 +4472,26 @@ def test_pad_constant(self):
assert actual.shape == (7, 4, 5)
assert_identical(actual, expected)

ar = xr.DataArray([9], dims="x")

actual = ar.pad(x=1)
expected = xr.DataArray([np.NaN, 9, np.NaN], dims="x")
assert_identical(actual, expected)

actual = ar.pad(x=1, constant_values=1.23456)
expected = xr.DataArray([1, 9, 1], dims="x")
assert_identical(actual, expected)

if LooseVersion(np.__version__) >= "1.20":
with pytest.raises(ValueError, match="cannot convert float NaN to integer"):
ar.pad(x=1, constant_values=np.NaN)
else:
actual = ar.pad(x=1, constant_values=np.NaN)
expected = xr.DataArray(
[-9223372036854775808, 9, -9223372036854775808], dims="x"
)
assert_identical(actual, expected)

def test_pad_coords(self):
ar = DataArray(
np.arange(3 * 4 * 5).reshape(3, 4, 5),
Expand Down

0 comments on commit ec7f628

Please sign in to comment.