How to make numpy array column sum up to 1

后端 未结 2 1397
故里飘歌
故里飘歌 2021-01-04 11:45

I am working on building a transition matrix for implementing the PageRank algorithm. How could I use numpy to make sure that the columns add up to one.

For example:

2条回答
  •  时光取名叫无心
    2021-01-04 12:50

    for i in range(len(A[0])):
        col_sum = A[:, i].sum()
        if col_sum != 0:
            A[:, i] = A[:, i]/col_sum
        else: 
            pass
    

    The for loop is a bit sloppy and I'm sure there's a much more elegant way but it works.
    Replace pass with A[:, i] = 1/len(A[0]) to eliminate dangling nodes and make the matrix column stocastic.

提交回复
热议问题