Reputation:
How can i use two for loops to replace the values in x with the row number, starting at 1, so it should be [[1,1,1,1,1],[2,2,2,2,2] … [5,5,5,5,5]]
x=np.ones((5,5)) print(x)
Thanks
Upvotes: 0
Views: 23
Reputation: 260690
Don't use for
loops in numpy, use broadcasting:
x=np.ones((5,5))
x[:] = np.arange(x.shape[0])[:, None]+1
Updated x
:
array([[1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2.],
[3., 3., 3., 3., 3.],
[4., 4., 4., 4., 4.],
[5., 5., 5., 5., 5.]])
Alternatives:
x[:] = np.arange(x.shape[0])[:, np.newaxis]+1
Or:
x[:] = np.arange(x.shape[0]).reshape(-1, 1)+1
Upvotes: 2