You need to enable JavaScript to run this app. 使用pandas与matplotlib绘制气体浓度日变化图时报TypeError错误
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas与matplotlib绘制气体浓度日变化图时报TypeError错误

错误原因
  • 调用groupby('Time').describe()得到的结果默认索引为时间(00:00这类字符串),列是两层MultiIndex,第一层为污染物名称,第二层为count/mean/std等统计指标
  • 多余的unstack()操作会把列的两层索引也转为行索引,最终DataFrame的索引变为三层结构(污染物名, 统计量名, 时间),导致传入matplotlib的x轴数据为元组而非字符串,触发类型错误。同时你尝试用data['NOx']['mean']取数也无法匹配到正确的层级结构。
修正代码(基础日变化绘图)
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = pd.DataFrame( 
    columns = ['From Date',   'NO',          'NO2',       'NOx',    'CO',           'Ozone'],           
    data = [
        ['2018-12-30 00:00:00', 5.856666,    39.208341,   28.97,   331.280881,  19.778900],
        ['2018-12-30 01:00:00', 4.050059,    16.262145,   13.53,   454.031703,  25.075286],
        ['2018-12-30 02:00:00', 4.057806,    15.293990,   12.96,   466.502681,  24.825294],
        ['2018-12-30 03:00:00', 3.835476,    13.526193,   11.71,   446.526784,  25.033312],
        ['2018-12-30 04:00:00', 4.230690,    11.251531,   10.70,   355.638469,  25.748796]
    ]
)
data["From Date"]= pd.to_datetime(data["From Date"])
data.set_index('From Date',inplace=True)
data.replace('NoData', np.nan, inplace= True)

# 提取时间和月份字段
data['Time'] = data.index.strftime("%H:%M")
data['Month'] = data.index.strftime("%Y-%m")

# 直接分组计算统计量,无需多余的索引修改和unstack操作
diurnal_stats = data.groupby('Time').describe()

fig, ax = plt.subplots(1, figsize=(12,6))
ax.set_title('Diurnal Profile', fontsize=14)
ax.set_ylabel('Gas Concentrations', fontsize=14, weight='bold')
ax.set_xlabel('Time of Day', fontsize=14)
# 从两层列索引中取对应污染物的均值
ax.plot(diurnal_stats.index, diurnal_stats['NOx']['mean'], 'g', linewidth=2.0)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
扩展:逐月生成日变化曲线

匹配你需要计算逐月污染物日变化的需求,可直接按Month和Time两层分组实现:

# 按月份+时间分组计算统计量
monthly_diurnal = data.groupby(['Month', 'Time']).describe()

# 遍历每个月份单独绘图
for month in monthly_diurnal.index.get_level_values('Month').unique():
    fig, ax = plt.subplots(1, figsize=(12,6))
    ax.set_title(f'{month} NOx Diurnal Profile', fontsize=14)
    ax.set_ylabel('NOx Concentrations', fontsize=14, weight='bold')
    ax.set_xlabel('Time of Day', fontsize=14)
    # 提取对应月份的统计数据
    plot_data = monthly_diurnal.loc[month]
    ax.plot(plot_data.index, plot_data['NOx']['mean'], 'g', linewidth=2.0)
    plt.xticks(rotation=45)
    plt.tight_layout()
    # 按需添加 plt.savefig(f'{month}_nox_diurnal.png') 保存图片到本地
    plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 07:27:03