Reputation:
I'm new to Python.
I have a numpy array of 3 columns and 50 rows. I want to add a value drawn from a normally distributed distribution to every number in the array except the first row. I am curious to know if there is a cleaner but also readable way to do this compared what I am currently doing? At the moment I'm using perhaps the not so elegant way:
nRows = np.shape (data)[0]
nCols = np.shape (data)[1]
x = data[0,:].copy() # Copy the first row
# Add a random number to all rows but 0
for i in range (nCols):
data[:,i] += np.random.normal (0, 0.8, nRows)
data[0,:] = x # Copy the first row back
Upvotes: 0
Views: 68
Reputation: 214987
You can assign values to indexed array. For your case, generate the 2d random array first and then directly add it to sliced data
:
data[1:] += np.random.normal(0, 0.8, (nRows - 1, nCols))
Upvotes: 1