Python 如何将Pandas时间戳转换为Matplotlib';什么是64格式?
下面的代码以Python 如何将Pandas时间戳转换为Matplotlib';什么是64格式?,python,pandas,matplotlib,Python,Pandas,Matplotlib,下面的代码以毫秒为单位绘制时间序列。 但是,Matplotlib在内部将此毫秒时间戳存储为float64,以便我可以将其重新格式化为hh:mm:ss,如下所示。有人知道如何手动将Pandas时间戳转换为Matplotlib的float64格式吗?谢谢 import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates x = np.arange(5000
毫秒
为单位绘制时间序列。
但是,Matplotlib在内部将此毫秒
时间戳存储为float64
,以便我可以将其重新格式化为hh:mm:ss
,如下所示。有人知道如何手动将Pandas时间戳转换为Matplotlib的float64
格式吗?谢谢
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
x = np.arange(5000)
df = pd.DataFrame(x, columns=['y'])
df['timestamp'] = pd.to_datetime(df.index, unit='ms')
df.set_index('timestamp', inplace=True)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(df.index, df.y)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
Matplotlib以float64格式存储日期
mdates.date2num()
也不起作用
最后更新:
对不起,我错了。
mdates.date2num()
确实有效!起初我以为ax.get_xlim()
返回的是(x[0],x[-1])
,但它实际上返回x[0]之前的某个值,以及x[-1]之后的某个值,因此该图在线条周围有一些填充。这就是为什么它返回(-2.892939814814815e-06,6.07517361111111E-05)
,而不是(0.0,5.785879629629629e-05)
。现在我终于明白了。谢谢大家 函数mdates.num2date()
用于转换为matplotlib管理的时间。 请参阅
这会有帮助-抱歉,to_pydatetime()
对您的回复不起作用,但我想将熊猫日期转换为matplotlib num,例如从1970-01-01 00:00:00
到-2.892939814814815e-06
您可以使用mdates.date2num(df.index[1]将日期转换为数字)
。我已经尝试了你的建议,答案不一样。通过get_xlim()
获得的第一个值指示图形上原点的值,因此该值在1970年之前,实际值为1969-12-31 23:59:59.750050+00:00。你说什么不适合什么?嗨@r-初学者,我想你是对的,get\u xlim()
不会返回x[0]
和x[-1]
。我想我现在终于明白了。非常感谢^_^
print(ax.get_xlim())
>> (-2.892939814814815e-06, 6.075173611111111e-05)
print(type(ax.get_xlim()[0]))
>> numpy.float64
print(df.index[0]) # how to convert to -2.892939814814815e-06
>> 1970-01-01 00:00:00
print(df.index[-1]) # how to convert to 6.075173611111111e-05
>> 1970-01-01 00:00:04.999000
print(mdates.date2num(df.index[0]))
>> 0.0
print(mdates.date2num(df.index[-1]))
>> 5.785879629629629e-05
# print xlim in Matplotlib format
print(ax.get_xlim())
ts = mdates.num2date(ax.get_xlim()[0])
ts1 = mdates.num2date(ax.get_xlim()[1])
print(ts)
print(ts1)