簡體   English   中英

從csv數據集創建python中的鄰接矩陣

[英]Create adjacency matrix in python from csv dataset

我的數據格式如下:

eventid    mnbr
20         1
26         1
12         2
14         2
15         3
14         3
10         3

eventid是一個成員參加數據的事件被表示為一個小組,因此您可以看到每個成員參加多個活動,多個成員可以參加同一個活動。 我的目標是創建一個鄰接矩陣,顯示:

 mnbr  1    2    3
 1     1    0    0
 2     0    1    1
 3     0    1    1

只要兩名成員參加同一活動,就會有1。 我成功地將csv文件的列讀入2個獨立的1D numpy數組。 然而,在這里,我不確定如何繼續。 如何使用第2列創建矩陣,以及如何使用第1列填充值? 我知道我沒有發布任何代碼,並且不期望在這方面有任何解決方案,但會非常感謝如何以有效的方式解決問題。 我有大約300萬個觀測值,因此創建太多外部變量會有問題。 提前致謝。 我收到一條通知,說我的問題可能是重復的,但我的問題是解析數據而不是創建鄰接矩陣。

這是一個解決方案。 它不直接為您提供所請求的鄰接矩陣,而是為您提供自己創建它所需的內容。

#assume you stored every line of your input as a tuples (eventid, mnbr).
observations = [(20, 1), (26, 1), (12, 2), (14, 2), (15,3 ), (14, 3), (10, 3)]

#then creates an event link dictionary. i.e something that link every event to all its mnbrs
eventLinks = {}

for (eventid, mnbr) in observations :
    #If this event have never been encoutered then create a new entry in links
    if not eventid in eventLinks.keys():
        eventLinks[eventid] = []

    eventLinks[eventid].append(mnbr)

#collect the mnbrs
mnbrs = set([mnbr for (eventid, mnbr) in observations])

#create a member link dictionary. This one link a mnbr to other mnbr linked to it.
mnbrLinks = { mnbr : set() for mnbr in mnbrs }

for mnbrList in eventLinks.values() :
    #add for each mnbr all the mnbr implied in the same event.
    for mnbr in mnbrList:
        mnbrLinks[mnbr] = mnbrLinks[mnbr].union(set(mnbrList))

print(mnbrLinks)

執行此代碼會產生以下結果:

{1: {1}, 2: {2, 3}, 3: {2, 3}}

這是一個字典,其中每個mnbr都有一組相關的鄰接mnbrs 這實際上是一個鄰接列表,它是一個壓縮的鄰接矩陣。 您可以使用字典鍵和值作為行和列索引來擴展它並構建您請求的矩陣。

希望它有所幫助。 亞瑟。

編輯:我提供了一種使用鄰接列表的方法,讓您實現自己的鄰接矩陣構建。 但是,如果數據稀疏,您應該考慮真正使用此數據結構。 http://en.wikipedia.org/wiki/Adjacency_list

編輯2:添加代碼以將adjacencyList轉換為一個小的智能adjacencyMatrix

adjacencyList = {1: {1}, 2: {2, 3}, 3: {2, 3}}

class AdjacencyMatrix():

    def __init__(self, adjacencyList, label = ""):
        """ 
        Instanciation method of the class.
        Create an adjacency matrix from an adjacencyList.
        It is supposed that graph vertices are labeled with numbers from 1 to n.
        """

        self.matrix = []
        self.label = label

        #create an empty matrix
        for i in range(len(adjacencyList.keys())):
            self.matrix.append( [0]*(len(adjacencyList.keys())) )

        for key in adjacencyList.keys():
            for value in adjacencyList[key]:
                self[key-1][value-1] = 1

    def __str__(self):
        # return self.__repr__() is another possibility that just print the list of list
        # see python doc about difference between __str__ and __repr__

        #label first line
        string = self.label + "\t"
        for i in range(len(self.matrix)):
            string += str(i+1) + "\t"
        string += "\n"

        #for each matrix line :
        for row in range(len(self.matrix)):
            string += str(row+1) + "\t"
            for column in range(len(self.matrix)):
                string += str(self[row][column]) + "\t"
            string += "\n"


        return string

    def __repr__(self):
        return str(self.matrix)

    def __getitem__(self, index):
        """ Allow to access matrix element using matrix[index][index] syntax """
        return self.matrix.__getitem__(index)

    def __setitem__(self, index, item):
        """ Allow to set matrix element using matrix[index][index] = value syntax """
        return self.matrix.__setitem__(index, item)

    def areAdjacent(self, i, j):
        return self[i-1][j-1] == 1

m = AdjacencyMatrix(adjacencyList, label="mbr")
print(m)
print("m.areAdjacent(1,2) :",m.areAdjacent(1,2))
print("m.areAdjacent(2,3) :",m.areAdjacent(2,3))

此代碼提供以下結果:

mbr 1   2   3   
1   1   0   0   
2   0   1   1   
3   0   1   1   

m.areAdjacent(1,2) : False
m.areAdjacent(2,3) : True

暫無
暫無

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

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