1

If I want to create a 5x5 zero matrix with values of 10, 20, 30, 40 just above the diagonal I can do the following:

import numpy as np
np.diag((1+np.arange(4))*10,k=1)

but how can i replace the elements above the diagonal in a 5x5 random matrix with the same array 10, 20, 30, 40 ? I have tried to use the numpy where function which works with 1D arrays like:

import numpy as np
array1 = np.array([2, 2, 2, 0, 2, 0, 2])
print np.where(array1==0, 1, array1) 

but I cannot make it working in higher dimensions. I can manually assign the values, but i am looking for a better solution.

2 Answers 2

1

You can try advance indexing:

a = np.arange(25).reshape(5,5)

s = np.arange(len(a))
a[s[:-1], s[1:]] = [10,20,30,40]

Output:

array([[ 0, 10,  2,  3,  4],
       [ 5,  6, 20,  8,  9],
       [10, 11, 12, 30, 14],
       [15, 16, 17, 18, 40],
       [20, 21, 22, 23, 24]])
Sign up to request clarification or add additional context in comments.

Comments

1

Maybe this works. For example, for this array:

arr = np.random.rand(5,5)
print(arr)

[[0.63267449 0.81436882 0.49014052 0.85241815 0.39175126]
 [0.79926876 0.46784356 0.64146423 0.24392249 0.70449611]
 [0.28667995 0.58503395 0.80665148 0.84331471 0.10687276]
 [0.59349235 0.23448985 0.25971096 0.60335227 0.31760505]
 [0.10723313 0.44694671 0.99660858 0.31529209 0.42713487]]


with np.diag(arr, k=1) you get the diagonal above the main diagonal.

diag = np.diag(arr, k=1)

you can get the indexes of the elements in diag using np.isin(...) and then replace those entries with [10, 20, 30, 40 ].

idxs = np.isin(arr, diag).nonzero()
arr[idxs] = np.array([10, 20, 30, 40 ], dtype = np.float)
arr

array([[ 0.63267449, 10.        ,  0.49014052,  0.85241815,  0.39175126],
       [ 0.79926876,  0.46784356, 20.        ,  0.24392249,  0.70449611],
       [ 0.28667995,  0.58503395,  0.80665148, 30.        ,  0.10687276],
       [ 0.59349235,  0.23448985,  0.25971096,  0.60335227, 40.        ],
       [ 0.10723313,  0.44694671,  0.99660858,  0.31529209,  0.42713487]])

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.