3

I have a numpy array that looks like this:

[[1399   17    4    3    0    0    0    0]
 [  11  374    2    3    1    4    0    1]
 [   7    0  187    4    0    0    1    1]
 [   2    3    4  308    0    0    0    3]
 [   2    0    0    0  280    3    0    1]
 [   0    2    0    0    2   81    0    3]
 [   1    0    2    0    2    0  154    4]
 [   0    0    1    2    1    1    8  552]]

I want to replace the values where [x,x] that is the column and row number are the same, to np.nan. I have tried doing this:

for i in range(8):
    data[i][i] = np.nan

but it gives an error

Many thanks

1 Answer 1

5

Use numpy.fill_diagonal after typing the array into float:

import numpy as np

arr = np.random.randint(0, 10, (10,10))
arr = arr.astype(float)
np.fill_diagonal(arr, np.nan)

Output:

array([[nan,  2.,  6.,  6.,  1.,  2.,  7.,  2.,  7.,  0.],
       [ 3., nan,  3.,  7.,  3.,  5.,  2.,  9.,  1.,  3.],
       [ 4.,  2., nan,  2.,  6.,  0.,  4.,  3.,  5.,  8.],
       [ 8.,  8.,  6., nan,  7.,  8.,  4.,  1.,  0.,  8.],
       [ 5.,  2.,  1.,  5., nan,  6.,  4.,  7.,  8.,  7.],
       [ 9.,  5.,  7.,  1.,  6., nan,  7.,  9.,  2.,  8.],
       [ 5.,  1.,  5.,  6.,  1.,  0., nan,  5.,  1.,  6.],
       [ 5.,  9.,  7.,  4.,  4.,  4.,  0., nan,  3.,  5.],
       [ 8.,  2.,  2.,  0.,  4.,  5.,  2.,  2., nan,  3.],
       [ 7.,  4.,  9.,  4.,  5.,  4.,  2.,  4.,  0., nan]])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. One question, how would I later on remove the decimal points, and turn each value back to integer? doing the same conversion to integer seems to be wrong, that is if I do data = data.astype(int) afterwards
nan recognizer as a float. you can't convert it to integer.

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.