[英]"keyerror" when trying to access a node attribute in networkx
我有一個推特粉絲網絡。 每個追隨者都有多個屬性,如追隨者計數、用戶名、位置等。我試圖找到圖中所有前驅節點的追隨者計數。 我可以使用 networokx 中的predecessor
函數來執行此操作,但是當我嘗試訪問節點屬性時,我在關注者計數上遇到“關鍵錯誤”。 繼承人我的代碼
if len(list(DG.predecessors(node))) > 0: #only loop through nodes that have 1 or more predecsoor
for pred_node in DG.predecessors(node):
a = DG.nodes[pred_node]['follower_count'] # Key value error here
當我嘗試將其分配給
這可以歸結為我如何設置屬性嗎? 作為參考,請參閱下面的代碼以了解我如何設置屬性
import csv
import networkx as nx
with open('twitter_nodelist.csv', 'r') as nodecsv: # Open the file
nodereader = csv.reader(nodecsv) # Read the csv
nodes = [n for n in nodereader][1:]
node_names = [n[0] for n in nodes] # Get a list of only the node names
with open('twitter_edgelist.csv', 'r') as edgecsv: # Open the file
edgereader = csv.reader(edgecsv) # Read the csv
edges = [tuple(e) for e in edgereader][1:] # Retrieve the data
print(len(node_names))
print(len(edges))
DG = nx.Graph()
DG.add_nodes_from(node_names)
DG.add_edges_from(edges)
total_nodes = DG.number_of_nodes()
print(nx.info(DG))
print(total_nodes)
username_dict = {}
user_screen_name_dict = {}
tweetid_dict = {}
tweet_text_dict = {}
user_followers_count_dict = {}
user_friends_count_dict = {}
user_location_dict = {}
user_url_dict = {}
tweet_created_at_dict = {}
tweet_source_dict = {}
for node in nodes: # Loop through the list, one row at a time
username_dict[node[0]] = node[1]
user_screen_name_dict[node[0]] = node[2]
tweet_text_dict[node[0]] = node[3]
user_followers_count_dict[node[0]] = node[4]
user_friends_count_dict[node[0]] = node[5]
user_location_dict = node[6]
user_url_dict = node[7]
tweet_created_at_dict = node[8]
tweet_source_dict = node[9]
nx.set_node_attributes(G, username_dict, 'username')
nx.set_node_attributes(G, user_screen_name_dict, 'screen_name')
nx.set_node_attributes(G, tweet_text_dict, 'tweet_text')
nx.set_node_attributes(G, user_followers_count_dict, 'follower_count')
nx.set_node_attributes(G, user_friends_count_dict, 'friend_count')
nx.set_node_attributes(G, user_location_dict, 'location')
nx.set_node_attributes(G, user_url_dict, 'URL')
nx.set_node_attributes(G, tweet_created_at_dict, 'tweet_creation_time')
nx.set_node_attributes(G, tweet_source_dict, 'tweet_source')
我試過打印字典,它們打印沒有問題
提前致謝
弄清楚了。 原來我沒有正確設置節點屬性。 我使用 G 而不是 DG
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.