How to combine a numpy array?

I have a numpy array as shown below:

data = [ 1.60130719e-01, 9.93827160e-01, 3.63108206e-04] np.around(data,2) # doesn't work any alternatives ? 

I want to get 2 decimal points for the values ​​above.

I see np.around , it works for a single value, but not for the whole array.

Is there any easy way to work in numpy or do I need to write my own function using np.around?

Update- The array was not an np array, after import, like np.array, it worked.

+22
source share
2 answers

You can use any

 np.round(data, 2) 

or

 np.around(data, 2) 

how equivalent they are.


The round documentation points to the documentation for around :

numpy.around(a, decimals=0, out=None)

Evenly round to the specified number of decimal places.


The reason you think the above methods do not work is because you imported numpy. In the first example, you define arrays only with array(...) . However, you then try to use np.round(...) !

You must stick to importing all methods into the global namespace with * ; or it is preferable to use the documentation standard through import as np :

 from numpy import * #bad import numpy as np #good 

If you try to exchange between using np.some_func(...) and just some_func(...) in another code, this will lead to confusion. Import as np is the way to go.


References:

+25
source

If you want the output to be

 array([1.6e-01, 9.9e-01, 3.6e-04]) 

the problem is not with the missing NumPy function, but with the fact that this kind of rounding is not standard. You can make your own rounding function, which achieves this as follows:

 def my_round(value, N): exponent = np.ceil(np.log10(value)) return 10**exponent*np.round(value*10**(-exponent), N) 

For general handling of solution 0 and negative values, you can do something like this:

 def my_round(value, N): value = np.asarray(value).copy() zero_mask = (value == 0) value[zero_mask] = 1.0 sign_mask = (value < 0) value[sign_mask] *= -1 exponent = np.ceil(np.log10(value)) result = 10**exponent*np.round(value*10**(-exponent), N) result[sign_mask] *= -1 result[zero_mask] = 0.0 return result 
+3
source

Source: https://habr.com/ru/post/1272965/


All Articles