Python读取CSV数据绘制饼图遇TypeError报错求助
Hey there! Let's break down what's going wrong with your code and fix it step by step.
The Core Problem
The main issue is that you're overwriting your lists instead of appending to them inside the loop. When you do Party = row[0], you're replacing the empty list with a single string (the party name from the current row). By the end of the loop, Party is just the last party name, Votes is just the last vote count (as a string), and plt.pie can't handle a single value—it needs a list of values to create slices. That's why you're getting the numpy.float64 has no len() error.
Corrected Code
First, let's fix the list appending. We'll also convert the numeric columns (Seats and Votes) to integers since they're counts, and use a with statement to safely handle the file (it auto-closes when done):
import matplotlib.pyplot as plt import csv # Initialize empty lists Party = [] Seats = [] Votes = [] # Use 'with' to open the file safely with open("vote_results.csv", "r") as outfile: file = csv.reader(outfile) # Skip the header row next(file, None) # Append each row's data to the lists for row in file: Party.append(row[0]) # Convert Seats and Votes to integers Seats.append(int(row[1])) Votes.append(int(row[2])) # Create the pie chart plt.pie(Votes, labels=Party, autopct='%1.1f%%') # Add percentages for clarity plt.title("Vote Distribution by Party") plt.show()
Handling Space-Separated CSV
If your CSV uses spaces instead of commas (like your example Party1 50 1000), you need to tell csv.reader to use spaces as the delimiter. Modify the csv.reader line like this:
file = csv.reader(outfile, delimiter=' ')
This will split each row correctly into the three columns.
Why This Works
- Appending to lists: Now
Partyis a list of all party names, andVotesis a list of integers representing each party's vote count—exactly whatplt.pieneeds to create multiple slices. - Numeric conversion: Converting
row[1]androw[2]to integers ensures matplotlib can process the values correctly for the pie chart. - Safe file handling: The
withstatement ensures the file is closed properly even if an error occurs.
Give this a try, and your pie chart should render correctly!
内容的提问来源于stack exchange,提问作者J. Smith

