Can I use numpy to replace values in an array, rather than generating a new array?

Tags: , ,

I feel like this can be easily accomplished. I have the following code:

my_array =   np.zeros(6)
min =      0
max =      1

my_array = np.random.uniform(min,max, my_array.shape)

I might be wrong, but I think np.random.uniform() generates a whole new array, and then the my_array variable simply points to the new array, while the old array gets garbage collected. Since I’m positive that the new array will have the same shape of the old one, is there a way to efficiently replace the values, rather than allocating a whole new array. Furthermore, I hope I could do this efficiently, such that I don’t need to use for loops. The following code was my attempt:

my_array[:] = np.random.uniform(min,max)

However, this results in a single new random value that gets reproduced 6 times, which is not what I want, and, furthermore, probably results in 6 calls to np.random.uniform() which seems inefficient

EDIT: I want to keep the same functionality as in the code above, i.e., I want to replace all values of the array with new, random, values. The idea is to do this multiple times which is why I want to avoid having to generate a new array each time


One can replace the values of one numpy array with the values of another numpy array using the syntax

original_array[...] = array_of_new_values

The ... is an Ellipsis. See for more information. As hpaulj comments, some numpy functions provide an out= argument, so values from the function can go directly into the existing array. np.random.uniform does not have this argument.

I have provided an example below.

import numpy as np

arr = np.zeros((100, 100, 100))

And now we overwrite the values:

low, high = 0, 1
arr[...] = np.random.uniform(low, high, arr.shape)

Here are timeit results of overwriting an existing array and creating a new variable:

%timeit arr[...] = np.random.uniform(0, 1, arr.shape)
# 67 ms ± 6.62 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
arr2 = np.random.uniform(0, 1, arr.shape)
# 85.3 ms ± 10.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Source: stackoverflow