0

I have a numpy array:

array([[ 0,  1,  2,  3,  4,  5,  6],
       [14, 15, 16, 17, 18, 19, 20],
       [28, 29, 30, 31, 32, 33, 34]])

I want to divide elementwise by 10 and then round elementwise (<0.5 rounding down to 0).

3
  • Just do it? np.round(array / 10) This will be subject to a slightly different rounding bahaviour than you specified (depending on the python version) but this will only affect .5 values Commented Apr 6, 2016 at 14:00
  • This produces the error:TypeError: unsupported operand type(s) for /: 'list' and 'int'. Commented Apr 6, 2016 at 14:04
  • yes, I used numpy.asarray. cheers Commented Apr 6, 2016 at 14:07

2 Answers 2

1

try:

import numpy as np

array = np.array([[ 0,  1,  2,  3,  4,  5,  6],
                  [14, 15, 16, 17, 18, 19, 20],
                  [28, 29, 30, 31, 32, 33, 34]], dtype=float)
result = np.round(array / 10)

result will be array([[ 0., 0., 0., 0., 0., 0., 1.], [ 1., 2., 2., 2., 2., 2., 2.], [ 3., 3., 3., 3., 3., 3., 3.]])

Sign up to request clarification or add additional context in comments.

Comments

0

There is a rounding function in numpy that can take care of rounding: numpy.round():

import numpy as np

array = np.array([[ 0,  1,  2,  3,  4,  5,  6],
                  [14, 15, 16, 17, 18, 19, 20],
                  [28, 29, 30, 31, 32, 33, 34]])

np.round(array / 10)

# array([[ 0.,  0.,  0.,  0.,  0.,  0.,  1.],
#        [ 1.,  2.,  2.,  2.,  2.,  2.,  2.],
#        [ 3.,  3.,  3.,  3.,  3.,  3.,  3.]])

this will however round x.5 (if x is even) down but y.5 (if y is odd) up. See the notes in np.around()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.