How do I create an numpy array of shape (120,120), with the first 7 values being 0.924 and the rest of the values being 0.53.I need this for a matrix in matplotlib
2 Answers
The fastest way is probably to create an empty array, fill it with a constant value, and update the few values that need to be updated:
>>> x = np.empty((120, 120))
>>> x.fill(0.53)
>>> x[0,:7] = 0.924
>>> x
array([[ 0.924, 0.924, 0.924, ..., 0.53 , 0.53 , 0.53 ],
[ 0.53 , 0.53 , 0.53 , ..., 0.53 , 0.53 , 0.53 ],
[ 0.53 , 0.53 , 0.53 , ..., 0.53 , 0.53 , 0.53 ],
...,
[ 0.53 , 0.53 , 0.53 , ..., 0.53 , 0.53 , 0.53 ],
[ 0.53 , 0.53 , 0.53 , ..., 0.53 , 0.53 , 0.53 ],
[ 0.53 , 0.53 , 0.53 , ..., 0.53 , 0.53 , 0.53 ]])
Comments
--> x = np.array([0.53]*(120*120)).reshape(120,120)
--> x[0,:7] = 0.924
Will fill the first 7 values in the first row as 0.924, swap the 0 and :7 in the index to get the first 7 in the first column as 0.924
2 Comments
Jaime
Don't do this! You are creating a 14,400 item long Python list, which is then parsed by numpy to find out its length and dtype, allocate an array and then copy the list data into it. See @EOL's answer for the better approach to this.
Eric O. Lebigot
While @Jaime is right about why this approach is relatively slow, I must say that it has the advantage of being a quite legible one-liner; I would use it if speed is not too much of a concern. A similar, and probably faster one-line solution would be
x = np.ones((120, 120))*0.53. (The fastest of the three is that of my answer, as it only involves simple and fast value settings.)