簡體   English   中英

將矩陣中的特定條目與 numpy 相加

[英]Sum specific entries in matrix with numpy

我想請你幫忙解決下一個問題。

我有一個鄰接矩陣作為 numpy 數組:

np.array([[ 0, 1, 2, 3],
          [ 1, 0, 6, 0],
          [ 2, 6, 0, 1],
          [ 3, 0, 1, 0]])

然后我想對節點列表之間的邊的權重求和,例如:

sum_edeges_between_list([0,1]) = 1 # only one entry, matrix[0,1]
sum_edeges_between_list([0,1,2]) = 9 # sum of three entries, matrix[0,1] +  matrix[0,2] +  matrix[1,2]
sum_edeges_between_list([0,1,2,3]) = 13 # sum of all entries above main diagonal

我怎樣才能做到這一點?

預先感謝!

您可以使用numpy.ix_獲取數組的相關部分並計算總和。

import numpy as np
a = np.array([[ 0, 1, 2, 3],
          [ 1, 0, 6, 0],
          [ 2, 6, 0, 1],
          [ 3, 0, 1, 0]])


def sum_edges_between_list(a, L):
    """
    >>> sum_edges_between_list(a, [0,1])
    1
    >>> sum_edges_between_list(a, [0,1,2])
    9
    >>> sum_edges_between_list(a, [0,1,2,3])
    13
    """
    return (a[np.ix_(L, L)].sum() / 2).astype(a.dtype)

你可以試試這個:

import numpy as np
from itertools import chain, combinations
def all_subsets(ss):
    return list(chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1))))

matx=np.array([[ 0, 1, 2, 3],
          [ 1, 0, 6, 0],
          [ 2, 6, 0, 1],
          [ 3, 0, 1, 0]])

def sum_edeges_between_list(ls):
    comb = [i for i in all_subsets(ls) if len(i)==2]
    return sum([matx[i[0]][i[1]] for i in comb])


print(sum_edeges_between_list([0,1]))
print(sum_edeges_between_list([0,1,2]))
print(sum_edeges_between_list([0,1,2,3]))

Output:

1
9
13

使用一些板載工具和一些切片怎么樣?

import numpy as np

x = np.array([[ 0, 1, 2, 3],
              [ 1, 0, 6, 0],
              [ 2, 6, 0, 1],
              [ 3, 0, 1, 0]])

def sum_edeges_between_list(ics):

    # crop the elements using the upper-triangle function and slicing
    a = np.triu(x[ics[0]:(ics[-1] + 1), ics[0]:(ics[-1] + 1)], 0)

    return a.sum()

小心:這只需要傳遞的列表的第一個和最后一個元素,並將它們之間的元素相加。

受到這個答案的啟發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM