Copy upper triangle to lower triangle in a python matrix

后端 未结 5 1706
耶瑟儿~
耶瑟儿~ 2020-12-24 01:31
       iluropoda_melanoleuca  bos_taurus  callithrix_jacchus  canis_familiaris
ailuropoda_melanoleuca     0        84.6                97.4                44
bos_tau         


        
5条回答
  •  醉梦人生
    2020-12-24 02:12

    The easiest AND FASTEST (no loop) way to do this for NumPy arrays is the following:

    The following is ~3x faster for 100x100 matrices compared to the accepted answer and roughly the same speed for 10x10 matrices.

    import numpy as np
    
    X= np.array([[0., 2., 3.],
                 [0., 0., 6.],
                 [0., 0., 0.]])
    
    X = X + X.T - np.diag(np.diag(X))
    print(X)
    
    #array([[0., 2., 3.],
    #       [2., 0., 6.],
    #       [3., 6., 0.]])
    
    

    Note that the matrix must either be upper triangular to begin with or it should be made upper triangular as follows.

    rng = np.random.RandomState(123)
    X = rng.randomint(10, size=(3, 3))
    print(X)
    #array([[2, 2, 6],
    #       [1, 3, 9],
    #       [6, 1, 0]])
    
    X = np.triu(X)
    X = X + X.T - np.diag(np.diag(X))
    print(X)
    #array([[2, 2, 6],
    #       [2, 3, 9],
    #       [6, 9, 0]])
    

提交回复
热议问题