My question is about the isinstance function but I'll give an example:
I am trying to implement min-max normalization in pandas, and specifically I need to be able to set arbitrary max and min values.
The following code seems to work:
def normalize_parameter(
array,
fill_na=True,
min_bound=True,
max_bound=True,
feature_range=(0, 1),
reverse=False
):
""" Min-max normalization.
Parameters
----------
array : pd.Series
column to normalize
fill_na : bool
NaN policy: fillna with 0 (True) or not (False)
min_bound, max_bound : bool
min and max values, default (min, max values of an array)
feature_range : tuple (min, max), default=(0, 1)
scale of normalization
reverse : bool, default=False
"""
s = array.fillna(0) if fill_na else array
if isinstance(min_bound, bool):
min_bound = s.min()
if isinstance(max_bound, bool):
max_bound = s.max()
print(f"{feature_range=}; bounds: {min_bound=}, {max_bound=}; nan policy: {fill_na=}")
_min, _max = feature_range
min_max_normalization = _min + ((s - min_bound) * (_max - _min) / (max_bound - min_bound))
return 1 - min_max_normalization if reverse else min_max_normalization
# takes min and max values of an array
normalize_parameter(array)
# takes min value of an array and max value of 1
normalize_parameter(array, max_bound=1)
But I feel this part specifically could be changed and be more pythonic.
if isinstance(min_bound, bool):
min_bound = s.min()
I thought this would work:
min_bound = min_bound or s.min()
But it doesn't if min_bound = 0 as 0 == False.
Do you think there's a better way or should I stick to isinstance?