@@ -4401,6 +4401,7 @@ def append(arr, values, axis=None):
4401
4401
4402
4402
4403
4403
def rescale (arr , out_min = 0 , out_max = 1 , in_min = None , in_max = None ,
4404
+ axis = None , return_params = False , out = None ):
4404
4405
"""Linearly scale non-NaN values in array to the specified interval.
4405
4406
4406
4407
.. versionadded:: 1.15.0
@@ -4426,6 +4427,10 @@ def rescale(arr, out_min=0, out_max=1, in_min=None, in_max=None,
4426
4427
axis : int, optional
4427
4428
Axis along which to scale `arr`. If `None`, scaling is done over
4428
4429
all axes.
4430
+ return_params : bool, optional
4431
+ If True, also return `offset` and `scale` parameters so that
4432
+ ``offset + scale * x`` maps ``x`` from input interval onto
4433
+ output interval.
4429
4434
out : array_like, optional
4430
4435
Array of the same shape as `arr`, in which to store the result.
4431
4436
@@ -4434,6 +4439,10 @@ def rescale(arr, out_min=0, out_max=1, in_min=None, in_max=None,
4434
4439
scaled_array : ndarray
4435
4440
Output array with the same shape as `arr` and all non-NaN values
4436
4441
scaled from interval [in_min, in_max] to [out_min, out_max].
4442
+ offset : scalar or ndarray, optional
4443
+ Only provided if `return_params` is True.
4444
+ scale : scalar or ndarray, optional
4445
+ Only provided if `return_params` is True.
4437
4446
4438
4447
Raises
4439
4448
------
@@ -4460,14 +4469,25 @@ def rescale(arr, out_min=0, out_max=1, in_min=None, in_max=None,
4460
4469
out_min = asanyarray (out_min )
4461
4470
out_max = asanyarray (out_max )
4462
4471
4472
+ keepdims = axis is not None # Avoids extra, unnecessary dims
4463
4473
if in_min is None :
4464
- in_min = np .nanmin (arr , axis = axis , keepdims = True )
4474
+ in_min = np .nanmin (arr , axis = axis , keepdims = keepdims ). astype ( float )
4465
4475
if in_max is None :
4466
- in_max = np .nanmax (arr , axis = axis , keepdims = True )
4476
+ in_max = np .nanmax (arr , axis = axis , keepdims = keepdims ). astype ( float )
4467
4477
4468
- res = (arr - in_min ) / (in_max - in_min ) * (out_max - out_min ) + out_min
4478
+ oldlen = in_max - in_min
4479
+ newlen = out_max - out_min
4480
+
4481
+ offset = (in_max * out_min - in_min * out_max ) / oldlen
4482
+ scale = newlen / oldlen
4483
+
4484
+ res = arr * scale + offset
4469
4485
4470
4486
if out is None :
4471
- return res
4472
- out [...] = res
4487
+ out = res
4488
+ else :
4489
+ out [...] = res
4490
+
4491
+ if return_params :
4492
+ return out , offset , scale
4473
4493
return out
0 commit comments