You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:如何从距离矩阵CSV构建带权重邻接表

Convert Distance Matrix CSV to Weighted Adjacency List in Python

Hey there! I get that turning a distance matrix CSV into an adjacency list can feel tricky when you're new to Python—let's break this down step by step so you can get exactly the format you want (like your example: AdjList = {1: [{Node2:11242, node5:1511}], 2:[{Node6:1024, Node10:985}], etc. }).

Option 1: Use Pandas (Easiest for CSV Handling)

Pandas is perfect for reading and manipulating tabular data like your distance matrix. If you don't have it installed yet, run pip install pandas first.

Step-by-Step Code

First, let's assume your CSV looks something like this (rows and columns are node identifiers, values are distances):

Node1,Node2,Node3,Node4
Node1,0,11242,0,1511
Node2,11242,0,1024,0
Node3,0,1024,0,985
Node4,1511,0,985,0

Here's the code to turn this into your desired adjacency list:

import pandas as pd

# Read the CSV, set the first column as the row index (node names)
distance_matrix = pd.read_csv("distance_matrix.csv", index_col=0)

# Initialize an empty adjacency list dictionary
adj_list = {}

# Loop through each node in the matrix
for current_node in distance_matrix.index:
    # Start with an empty list of neighbors for the current node
    neighbors = []
    # Check each potential neighbor node
    for neighbor_node in distance_matrix.columns:
        distance = distance_matrix.loc[current_node, neighbor_node]
        # Skip the node itself (distance is 0) and any non-existent edges (if your matrix uses 0 for no connection)
        if current_node != neighbor_node and distance > 0:
            # Add the neighbor and its weight as a dictionary entry in the neighbors list
            neighbors.append({neighbor_node: distance})
    # Assign the neighbors list to the current node in the adjacency list
    adj_list[current_node] = neighbors

# Print the result to verify
print(adj_list)

Customization Tips

  • If your nodes are numeric (like 1 instead of Node1), just convert the indices/columns to integers: current_node = int(current_node) and neighbor_node = int(neighbor_node) inside the loops.
  • If your matrix uses NaN or -1 to represent no connection, adjust the condition to if current_node != neighbor_node and pd.notna(distance) and distance != -1.

Option 2: Use Native Python CSV Module (No External Libraries)

If you don't want to install pandas, you can use Python's built-in csv module instead:

import csv

adj_list = {}

with open("distance_matrix.csv", "r") as csv_file:
    reader = csv.reader(csv_file)
    # Get the header row (these are the neighbor node names)
    header = next(reader)
    # Loop through each row in the CSV
    for row in reader:
        current_node = row[0]
        neighbors = []
        # Iterate over each distance value in the row
        for idx in range(1, len(row)):
            neighbor_node = header[idx]
            # Convert distance to integer/float (adjust based on your data type)
            distance = int(row[idx])
            # Skip self and non-edges
            if current_node != neighbor_node and distance > 0:
                neighbors.append({neighbor_node: distance})
        adj_list[current_node] = neighbors

print(adj_list)

Example Output

Using the sample CSV above, you'll get an output like:

{
    'Node1': [{'Node2': 11242}, {'Node4': 1511}],
    'Node2': [{'Node1': 11242}, {'Node3': 1024}],
    'Node3': [{'Node2': 1024}, {'Node4': 985}],
    'Node4': [{'Node1': 1511}, {'Node3': 985}]
}

This matches the structure you described—each key is a node, and the value is a list of dictionaries where each dictionary maps a neighbor node to its distance weight.

内容的提问来源于stack exchange,提问作者Vondoe79

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:33:16