Home > other >  Python numpy array values get rounded after boolean indexing
Python numpy array values get rounded after boolean indexing

Time:03-21

I want to apply calculation only for those values that are higher than threshold. After doing it with boolean indexing, values get rounded. How to prevent it?

starting_score = 1
threshold = 5
x = np.array([0,1,2,3,4,5,6,7,8,9,10])
gt_idx = x > threshold
le_idx = x <= threshold
decay = math.log(2) / 10
y = starting_score * np.exp(-decay * x)
x[gt_idx] = starting_score * np.exp(-decay * x[gt_idx])

y
array([1.        , 0.93303299, 0.87055056, 0.8122524 , 0.75785828,
       0.70710678, 0.65975396, 0.61557221, 0.57434918, 0.53588673,
       0.5       ])


x
array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0])

when applied to full array, I get correct y array. when applied to part of x, values get selected properly, but rounded to 0

My expected output is

 array([0, 1, 2, 3, 4, 5, 0.65975396, 0.61557221, 0.57434918, 0.53588673, 0.5])

CodePudding user response:

numpy automatically assigns the integer data type to x. To preserve your floats you need to change the type of the x array

x.dtype
# Out: dtype('int64')

x = x.astype('float64')

or declare x as an array of float64

x = np.array([0,1,2,3,4,5,6,7,8,9,10], dtype='float64')

CodePudding user response:

It is considered np.int32 as default type for when you create a NumPy array with integers as x. For getting other types in the results you have two ways:

# np.float32 or np.float64
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float64)  # way 1
x = x.astype(np.float64)                                            # way 2

such operation is not needed for y because in is multiplied by a float type value i.e. np.exp(-decay * x), so it became to float types.

CodePudding user response:

Adding .astype('float64') or .astype('float32') before last line like below: (you got rounded number because of type array x)

>>> x = x.astype('float64')
>>> x[gt_idx] = starting_score * np.exp(-decay * x[gt_idx])
>>> x
array([0.        , 1.        , 2.        , 3.        , 4.        ,
       5.        , 0.65975396, 0.61557221, 0.57434918, 0.53588673,
       0.5       ])
  • Related