@@ -45,7 +45,7 @@ class RoundingError(Exception):
45
45
pass
46
46
47
47
48
- def nice_round (arr , int_type , nan2zero = True ):
48
+ def nice_round (arr , int_type , nan2zero = True , infmax = False ):
49
49
""" Round floating point array `arr` to type `int_type`
50
50
51
51
Parameters
@@ -57,6 +57,12 @@ def nice_round(arr, int_type, nan2zero=True):
57
57
nan2zero : {True, False}
58
58
Whether to convert NaN value to zero. Default is True. If False, and
59
59
NaNs are present, raise RoundingError
60
+ infmax : {False, True}
61
+ If True, set np.inf values in `arr` to be `int_type` integer maximum
62
+ value, -np.inf as `int_type` integer minimum. If False, merely set infs
63
+ to be numbers at or near the maximum / minumum number in `arr` that can be
64
+ contained in `int_type`. Therefore False gives faster conversion at the
65
+ expense of infs that are further from infinity.
60
66
61
67
Returns
62
68
-------
@@ -67,12 +73,6 @@ def nice_round(arr, int_type, nan2zero=True):
67
73
--------
68
74
>>> nice_round([np.nan, np.inf, -np.inf, 1.1, 6.6], np.int16)
69
75
array([ 0, 32767, -32768, 1, 7], dtype=int16)
70
-
71
- Notes
72
- -----
73
- We always set +-inf to be the min / max of the integer type. If you want
74
- something different you'll need to filter them before passing to this
75
- routine.
76
76
"""
77
77
arr = np .asarray (arr )
78
78
flt_type = arr .dtype .type
@@ -85,4 +85,15 @@ def nice_round(arr, int_type, nan2zero=True):
85
85
iarr = np .clip (np .rint (arr ), mn , mx ).astype (int_type )
86
86
if have_nans :
87
87
iarr [nans ] = 0
88
+ if not infmax :
89
+ return iarr
90
+ # Deal with scalar as input
91
+ shape = iarr .shape
92
+ iarr = np .atleast_1d (iarr )
93
+ arr = np .atleast_1d (arr )
94
+ ii = np .iinfo (int_type )
95
+ iarr [arr == np .inf ] = ii .max
96
+ if ii .min != int (mn ):
97
+ iarr [arr == - np .inf ] = ii .min
98
+ iarr .shape = shape
88
99
return iarr
0 commit comments