0

Given a triangular matrix m in python how best to extract from it the value at row i column j?

m = [1,np.nan,np.nan,2,3,np.nan,4,5,6]
m = pd.DataFrame(np.array(x).reshape((3,3)))

Which looks like:

    0   1   2
0   1.0 NaN NaN
1   2.0 3.0 NaN
2   4.0 5.0 6.0

I can get lower elements easily m[2,0] returns 4.

But if I ask for m[0,2] i get nan when I would like 4 again.

What is the best way of accomplishing this with in python?

D A Wells
  • 1,047
  • 12
  • 16

2 Answers2

2

Use pandas.DataFrame.fillna with transpose:

m = m.fillna(m.T)
print(m)

Output:

     0    1    2
0  1.0  2.0  4.0
1  2.0  3.0  5.0
2  4.0  5.0  6.0

m.loc[0,2] == m.loc[2,0] == 4
# True

In case there are column names (like A,B,C):

m.where(m.notna(), m.T.values)

Output:

     A    B    C
0  1.0  2.0  4.0
1  2.0  3.0  5.0
2  4.0  5.0  6.0
Chris
  • 29,127
  • 3
  • 28
  • 51
0

The easiest way I have found to solve this is to make the matrix symmetrical, I learnt how from this answer.

There are a couple of steps:

  1. Convert nan to 0
m0 = np.nan_to_num(m)
  1. Add the transpose of the matrix to itself
m = m0 + m0.T
  1. Subtract the diagonal
m = m - np.diag(m0.diagonal())

Then m[0,2] and m[2,0] will both give you 4.

    0   1   2
0   1.0 2.0 4.0
1   2.0 3.0 5.0
2   4.0 5.0 6.0
D A Wells
  • 1,047
  • 12
  • 16