从CSV文件构建NetworkX社交网络图遇AttributeError问题求助
Hey there! Let's work through your NetworkX issues together—first fixing that annoying AttributeError, then getting those weighted edges to show up with the right thickness.
AttributeError: 'list' object has no attribute 'decode' Error The root cause here is that Python 3 strings are already Unicode-encoded, so there's no need to call decode() on them. But NetworkX 2.1 (which is a bit outdated) has leftover Python 2-era logic that tries to decode strings when it shouldn't—especially when handling data from csv.reader, which returns lists of Python 3 strings.
Looking at your code snippet, you've got the CSV read and graph initialized, but the error is almost certainly happening when you try to add edges from the CSV data. Instead of passing the raw reader object to a NetworkX import method (which triggers the problematic encoding code), let's manually parse each row and add edges directly:
import networkx as nx import csv # Initialize your undirected graph G = nx.Graph() # Read the CSV (assuming your format is: source_node, target_node, weight) with open('testest.csv', "r", encoding='utf8') as data_file: csv_reader = csv.reader(data_file) # Skip the header row if your CSV has one (remove this line if there's no header) next(csv_reader) # Loop through each row to add edges with weights for row in csv_reader: source, target, weight = row[0], row[1], float(row[2]) G.add_edge(source, target, weight=weight)
This bypasses the decode() error entirely by feeding NetworkX properly formatted Python 3 strings and numeric weights directly.
Once your graph is built correctly, adjusting edge thickness based on weight is straightforward. You just need to map each edge's weight to a width value when drawing the graph:
import matplotlib.pyplot as plt # Extract weights from all edges and scale them for visibility edge_weights = [G[u][v]['weight'] for u, v in G.edges()] # Scale the weights (multiply by a factor to make thickness differences more obvious) edge_widths = [weight * 2 for weight in edge_weights] # Draw the graph with weighted edge thickness nx.draw(G, with_labels=True, width=edge_widths) plt.show()
If your weight values are very small or large, tweak the scaling factor (the 2 in the example) to get the thickness look you want. You could also normalize weights to a fixed range (like 1-5) for more consistent results.
- Double-check your CSV format to ensure each row has exactly three values: source node, target node, and weight. If you don't have explicit weights, set a default value like
weight=1when adding edges. - Consider upgrading NetworkX to a newer version (2.6 or later) if possible—newer releases have better Python 3 compatibility and smoother plotting features.
内容的提问来源于stack exchange,提问作者Melissa

