Chris Parry
Chris Parry

Reputation: 3047

Manipulating nested numpy array

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).

Upvotes: 0

Views: 301

Answers (2)

Francesco Nazzaro
Francesco Nazzaro

Reputation: 2916

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.]])

Upvotes: 1

MSeifert
MSeifert

Reputation: 152597

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()

Upvotes: 0

Related Questions