Home > Net >  Replace rows in an MxN matrix with numbers from 1 to N
Replace rows in an MxN matrix with numbers from 1 to N

Time:11-30

Im interested in replacing all of my rows in an MxN matrix with values from 1 to N.

For example: [[4,6,8,9,3],[5,1,2,5,6],[1,9,4,5,7],[3,8,8,2,5],[1,4,2,2,7]]

To: [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

I've tried using loops going through each row individually but struggle to replace elements.

CodePudding user response:

Try:

lst = [
    [4, 6, 8, 9, 3],
    [5, 1, 2, 5, 6],
    [1, 9, 4, 5, 7],
    [3, 8, 8, 2, 5],
    [1, 4, 2, 2, 7],
]

for row in lst:
    row[:] = range(1, len(row)   1)

print(lst)

Prints:

[
    [1, 2, 3, 4, 5],
    [1, 2, 3, 4, 5],
    [1, 2, 3, 4, 5],
    [1, 2, 3, 4, 5],
    [1, 2, 3, 4, 5],
]

CodePudding user response:

As you tagged your question with numpy, I assume that your source array is a Numpy array.

So, for the test purpose, you can create it as:

arr = np.array([[4,6,8,9,3],[5,1,2,5,6],[1,9,4,5,7],[3,8,8,2,5],[1,4,2,2,7]])

Then, to fill each row with consecutive numbers, you can run:

arr[:] = np.arange(1, arr.shape[1]   1)

Due to Numpy broadcasting there is no need to use any loop to operate on consecutive rows.

The result is:

array([[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]])
  • Related