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

Python读取CSV数据绘制饼图遇TypeError报错求助

Fixing Your Pie Chart CSV Reading Issue

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 Party is a list of all party names, and Votes is a list of integers representing each party's vote count—exactly what plt.pie needs to create multiple slices.
  • Numeric conversion: Converting row[1] and row[2] to integers ensures matplotlib can process the values correctly for the pie chart.
  • Safe file handling: The with statement 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:51:35