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

Python matplotlib绘图如何仅展示符合条件的数值并解决类型报错

筛选指定站点温度绘图的报错修复

数据集样例

报错原因

你的筛选逻辑存在缺陷:

  • 仅对local_time列使用.where(df['location_id'] == 1)处理,不满足条件的行会被自动填充为浮点型NaN
  • temperature列未做同步筛选,保留了所有行的数值
  • 最终传入plt.plot()的x序列同时包含时间类型值和浮点型空值,matplotlib无法统一解析数据类型,触发类型报错。

修正代码

直接对整个DataFrame做行筛选,仅保留location_id = 1的记录,再从筛选结果中提取绘图需要的字段即可:

import matplotlib.pyplot as plt
import pandas as pd

# 筛选1号站点的所有数据
df_filtered = df[df['location_id'] == 1].copy()
# 若local_time列未解析为时间格式,添加该行转换,可避免x轴刻度重叠、乱序问题
df_filtered['local_time'] = pd.to_datetime(df_filtered['local_time'])

x = df_filtered['local_time']
y = df_filtered['temperature']

plt.plot(x, y)
plt.xlabel('Local time')
plt.ylabel('Temperature')
plt.title('Weather in London')
plt.show()

如果你坚持使用.where()方法,必须对x、y两列应用完全一致的筛选规则,保证两列空值位置对齐,否则依然会出现数据匹配问题,这种写法可读性远低于直接整表筛选,不推荐使用。

内容的提问来源于stack exchange,提问作者Elisa L.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 18:15:45