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

使用日期与整数构建散点图时遇TypeError问题求助

解决Matplotlib散点图绘制时的TypeError错误

错误原因

你的代码存在两个核心问题:

  • x = df2.loc[df2['timestamp'].str.startswith('2015')] 返回的是完整的筛选后DataFrame,而非单独的timestamp列,Matplotlib无法直接将DataFrame作为散点图的X轴数据,从而触发unhashable type: 'numpy.ndarray'错误。
  • y = df2['cnt'] 取的是全量租赁数据,和筛选后的X轴数据长度不匹配,即便没有前面的错误,也会导致绘图异常。

修正方案

方法1:先筛选数据集,再提取对应列

先将2015年的数据行单独筛选出来,再从子集中提取timestamp和cnt作为X、Y轴数据:

import pandas as pd
import matplotlib.pyplot as plt

path2 = r'C:\Users\bossd\OneDrive\Документы\pipirka.csv'
df2 = pd.read_csv(path2) 

# 筛选2015年的数据行
df_2015 = df2[df2['timestamp'].str.startswith('2015')]
# 提取对应列
x = df_2015['timestamp']
y = df_2015['cnt']

plt.scatter(x, y)
# 旋转X轴日期标签避免重叠
plt.xticks(rotation=45)
plt.xlabel('日期')
plt.ylabel('当日自行车租赁量')
plt.show()

方法2:直接提取筛选后的单列数据

一步到位,直接提取符合条件的timestamp和对应行的cnt:

import pandas as pd
import matplotlib.pyplot as plt

path2 = r'C:\Users\bossd\OneDrive\Документы\pipirka.csv'
df2 = pd.read_csv(path2) 

# 提取2015年的timestamp列
x = df2.loc[df2['timestamp'].str.startswith('2015'), 'timestamp']
# 提取对应行的cnt列
y = df2.loc[df2['timestamp'].str.startswith('2015'), 'cnt']

plt.scatter(x, y)
plt.xticks(rotation=45)
plt.xlabel('日期')
plt.ylabel('当日自行车租赁量')
plt.show()

测试验证

用你提供的测试数据运行上述代码,会正确绘制2015年5条数据的散点图:
测试数据代码:

data = {'timestamp': ['2015-01-04', '2015-01-05', '2015-01-06', '2015-01-07', '2015-01-08', '2016-12-27', '2016-12-28', '2016-12-29', '2016-12-30', '2016-12-31'],
        'cnt': [9234, 20372, 20613, 21064, 15601, 10842, 12428, 14052, 11566, 11424]}
df2 = pd.DataFrame(data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:57:17