import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
from datetime import datetime
import numpy as np

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

x = (df2.loc[df2['timestamp'].str.startswith('2015')])
y = df2['cnt']
plt.scatter(x,y)
plt.show()

我想用包含‘2015’作为x轴的日期和表示这一天自行车租赁的‘cnt’参数来构建一个散点图. 但在运行代码后,我收到以下错误

Cell In[47], line 14
     12 x = (df2.loc[df2['timestamp'].str.startswith('2015')])
     13 y = df2['cnt']
---> 14 plt.scatter(x,y)
     15 plt.show()
     17 display(df2)
...
File ~\venv\lib\site-packages\matplotlib\category.py:214, in UnitData.update(self, data)
    212 # check if convertible to number:
    213 convertible = True
--> 214 for val in OrderedDict.fromkeys(data):
    215     # OrderedDict just iterates over unique values in data.
    216     _api.check_isinstance((str, bytes), value=val)
    217     if convertible:
    218         # this will only be called so long as convertible is True.

TypeError: unhashable type: 'numpy.ndarray'

数据帧如下所示,其中包含时间戳作为日期,而不是这一天的自行车租赁量

# read the following sample data with
df2 = pd.read_html('https://stackoverflow.com/q/77090789/7758804')[0]
timestamp cnt
2015-01-04 9234
2015-01-05 20372
2015-01-06 20613
2015-01-07 21064
2015-01-08 15601
2016-12-27 10842
2016-12-28 12428
2016-12-29 14052
2016-12-30 11566
2016-12-31 11424

推荐答案

  • 应该首先将'timestamp'列转换为具有pd.to_datetime的DATETIME数据类型,否则DATETIME x-TICK将无法正确定位和格式化.
    • 典型流程应从清除数据开始,然后 Select .
  • x = (df2.loc[df2['timestamp'].str.startswith('2015')])是错误的原因,因为它 Select 整个数据帧,而不是数据帧的任何一列.并且没有为所需的年份 Select df2['cnt'].
  • pandas.DataFrame.plot使用matplotlib作为默认打印后端,并应用于绘制数据帧.
# load the data from the markdown table in the OP
df2 = pd.read_html('https://stackoverflow.com/q/77090789/7758804')[0]

# convert the column to a datetime dtype
df2.timestamp = pd.to_datetime(df2.timestamp)

# select the data by year
df_2015 = df2[df2.timestamp.dt.year.eq(2015)]

# directly plot the dataframe, which uses matplotlib as the back end
ax = df_2015.plot(x='timestamp', marker='.', ls='')

enter image description here

Python相关问答推荐

为什么自定义pytree aux_data对于jnp.数组来说在.jit()之后跟踪,而对于np.数组来说则不是?

修剪Python框架中的尾随NaN值

如何从格式为note:{neighbor:weight}的字典中构建networkx图?

Polars -转换为PL后无法计算熵.列表

Python:记录而不是在文件中写入询问在多文件项目中记录的最佳实践

如何根据条件在多指标框架上进行groupby

计算相同形状的两个张量的SSE损失

理解Python的二分库:澄清bisect_left的使用

如何在msgraph.GraphServiceClient上进行身份验证?

@Property方法上的inspect.getmembers出现意外行为,引发异常

Django管理面板显示字段最大长度而不是字段名称

DataFrame groupby函数从列返回数组而不是值

在Python中处理大量CSV文件中的数据

Julia CSV for Python中的等效性Pandas index_col参数

Python,Fitting into a System of Equations

从spaCy的句子中提取日期

UNIQUE约束失败:customuser. username

在Python 3中,如何让客户端打开一个套接字到服务器,发送一行JSON编码的数据,读回一行JSON编码的数据,然后继续?

* 动态地 * 修饰Python中的递归函数

如何获取Python synsets列表的第一个内容?