1

I'm looking for the shortest possible way to uniformly scale a float array like

orig_arr = [0.0, 0.2, 0.4, 0.6, 0.8]

to another range where 0.0 from this example is transformed to min and 0.8 is transformed to max.

Usually I'd do this by calculating componentwise:

new_arr[i] = new_rg_min + orig_arr[i] * (new_rg_max - new_rg_min)

But if there's some numpy or whatever function that can do this without the need of a loop...

or shorter: I'd like to linearly scale and move one range to another.

Hendrik Wiese
  • 2,010
  • 3
  • 22
  • 49

1 Answers1

3

With numpy you can just do math on the whole array at a time... for example your code can change to:

new_arr = numpy.array(orig_array) * (new_rg_max - new_rg_min) + new_rg_min

because multiplying or adding a scalar works element by element (and also does the same for multi-dimensional arrays).

For example I often scale result of computed images to 0..255 to save them as PGM files with:

mn = numpy.min(image)
mx = numpy.max(image)
output = numpy.uint8((image - mn)*255/(mx - mn))
6502
  • 112,025
  • 15
  • 165
  • 265