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.
相关产品推荐
相关产品推荐

