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

如何用For循环为Pandas DataFrame各年份生成带占比的充电设施饼图?

解决按年份生成充电设施占比饼图的问题

你的需求是遍历ev_aus DataFrame,为每一年生成快充(Publicly available fast)、慢充(Publicly available slow)的饼图并显示占比。原始数据如下:

region  powertrain  year    value
38  Australia   Publicly available fast 2017    40.0
39  Australia   Publicly available slow 2017    440.0
44  Australia   Publicly available fast 2018    61.0
45  Australia   Publicly available slow 2018    670.0
54  Australia   Publicly available fast 2019    250.0
55  Australia   Publicly available slow 2019    1700.0
60  Australia   Publicly available fast 2020    350.0
61  Australia   Publicly available slow 2020    2000.0
70  Australia   Publicly available fast 2021    350.0
73  Australia   Publicly available slow 2021    2000.0

你尝试的代码存在以下问题:

ev_aus.head(10)
for i in ev_aus['year'].value_counts():
    i.plot.pie(y='Powertrain', figsize = (5, 5), title = 'PowerTrain')

# p = ev_aus['powertrain'].value_counts()
# p.plot.pie(y='Powertrain', figsize = (5, 5), title = 'PowerTrain')
  • ev_aus['year'].value_counts()返回的是每年的记录数(比如2017对应2),并非按年份分组的数据切片,i是整数,没有plot方法
  • 列名大小写不一致:DataFrame中是powertrain,代码里写了Powertrain
  • 未按年份筛选对应数据,无法生成目标饼图

正确实现代码

import matplotlib.pyplot as plt

# 按年份分组遍历数据
for year, group in ev_aus.groupby('year'):
    group.plot.pie(
        y='value',
        labels=group['powertrain'],
        autopct='%1.1f%%',  # 显示百分比格式
        figsize=(5,5),
        title=f'充电设施占比 - {year}'
    )
    plt.show()  # 单独显示每个年份的饼图,避免重叠

代码说明

  • 用groupby('year')直接按年份分组,获取每个年份对应的子DataFrame
  • autopct='%1.1f%%'参数自动计算并显示各类型设施的百分比占比
  • 每个循环调用plt.show(),确保每个年份的饼图独立展示
  • 严格匹配DataFrame中的列名(powertrain、value)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:25:27