0

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

1
  • 2
    Why would you use for loops with numpy? It's an anti-pattern. Commented Dec 12, 2022 at 21:06

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

one nit -- use np.newaxis instead of None so it makes it a bit clearer what's happening
@jkr you're probably right, although np.newaxis just points to None ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.