Python 如何仅绘制datetime64[ns]属性的时间
我有一个长时间范围的数据帧,格式为Python 如何仅绘制datetime64[ns]属性的时间,python,pandas,datetime,plot,Python,Pandas,Datetime,Plot,我有一个长时间范围的数据帧,格式为datetime64[ns]和一个int值 数据如下所示: MIN_DEP DELAY 0 2018-01-01 05:09:00 0 1 2018-01-01 05:13:00 0 2 2018-01-01 05:39:00 0 3 2018-01-01 05:43:00 0 4 2018-01-01 06:12:00 34 ...
datetime64[ns]
和一个int值
数据如下所示:
MIN_DEP DELAY
0 2018-01-01 05:09:00 0
1 2018-01-01 05:13:00 0
2 2018-01-01 05:39:00 0
3 2018-01-01 05:43:00 0
4 2018-01-01 06:12:00 34
... ... ...
77005 2020-09-30 23:42:00 0
77006 2020-09-30 23:43:00 0
77007 2020-09-30 23:43:00 43
77008 2020-10-01 00:18:00 0
77009 2020-10-01 00:59:00 0
[77010 rows x 2 columns]
MIN_DEP datetime64[ns]
DELAY int64
dtype: object
目标是在x轴上绘制00:00-24:00范围内的所有数据,不再显示日期
当我试图绘制它时,时间线在任何点都是00:00。如何解决这个问题
import matplotlib.dates as mdates
fig, ax = plt.subplots()
ax.plot(pd_to_stat['MIN_DEP'],pd_to_stat['DELAY'])
xfmt = mdates.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(xfmt)
plt.show()
尝试将之前的时间戳转换为dt.time,然后绘制它
pd_to_stat['time'] = pd.to_datetime(pd_to_stat['MIN_DEP'], format='%H:%M').dt.time
fig, ax = plt.subplots()
ax.plot(pd_to_stat['time'],pd_to_stat['DELAY'])
plt.show()
Plot不允许这样做:
TypeError: float() argument must be a string or a number, not 'datetime.time'
根据您的要求,我想您不需要时间戳中的日期和秒字段。因此,首先需要进行一点预处理。 使用下面的代码删除秒字段
dataset['MIN_DEP'] = dataset['MIN_DEP'].strftime("%H:%M")
然后,您可以按照以下方式从时间戳中删除日期
dataset['MIN_DEP'] = pd.Series([val.time() for val in dataset['MIN_DEP']])
然后,您可以用通常的方式绘制数据。现在似乎可以了。我没认出,情节还在日期上分裂。要解决此问题,请使用DateFormatter将所有日期替换为同一日期并绘制它隐藏日期
import matplotlib.dates as mdates
pd_to_stat['MIN_DEP'] = pd_to_stat['MIN_DEP'].map(lambda t: t.replace(year=2020, month=1, day=1))
fig, ax = plt.subplots()
ax.plot(pd_to_stat['MIN_DEP'],pd_to_stat['DELAY'])
xfmt = mdates.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(xfmt)
plt.show()
谢谢!但是plot仍然说
TypeError:float()参数必须是字符串或数字,而不是“datetime.time”
在使用我的解决方案后,您可以打印数据集的类型['MIN_DEP'],并在后面提到什么是数据类型。类型是MIN_DEP object
事实上,您的解决方案与pd_to_to_stat['time']=pd.to_datetime(pd_to_stat['MIN_DEP'],格式='%H:%M').dt.time
我在文章末尾提到了它。