user11929190
user11929190

Reputation:

How to round a specific selection of numbers in numpy array?

From the random numpy list, I want to round only the numbers that are in the index of padInputs. The following code is something that I am trying but doesn't work. What would be a workaround?

padInputs = [0, 2, 7, 8]
random = np.random.rand(13)
for padInput in padInputs:
    np.around(random[padInput])

For example,

Input
[0.87720789, 0.88194004, 0.06039337, 0.13874861, 0.85552875]

Output
[0.87720789, 1, 0, 0.13874861, 0.85552875]

Upvotes: 2

Views: 118

Answers (3)

incarnadine
incarnadine

Reputation: 700

The following one-line piece of code can replace your for loop and does exactly what you want

np.put(random, padInputs, np.around(random))

Upvotes: 0

Dishin H Goyani
Dishin H Goyani

Reputation: 7693

Problem in your code is you have to assign result back to array as np.around is not in memory function. like

for padInput in padInputs:
    random[padInput] = np.around(random[padInput])

random
array([1.        , 0.53206402, 1.        , 0.18129529, 0.71238687,
       0.92995779, 0.21934659, 0.        , 1.        , 0.26042076,
       0.76826639, 0.82750894, 0.35687544])

but it should be replace by one line as @Bruno define in his answer.

Upvotes: 0

Bruno Mello
Bruno Mello

Reputation: 4618

Try this way:

random[padInputs] = np.around(random[padInputs])

Note that this will round without decimals, you can pass it as an argument to round in the following way:

random[padInputs] = np.around(random[padInputs], decimals=2)

Upvotes: 2

Related Questions