本文介绍了从 pandas 时间序列图中的Axes.get_xlim()获取可用日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从用熊猫创建的时间序列图中获取图的xlimits作为python datetime对象.使用ax.get_xlim()返回轴限制为numpy.float64,我不知道如何将数字转换为可用的日期时间.

I'm trying to get the xlimits of a plot as a python datetime object from a time series plot created with pandas. Using ax.get_xlim() returns the axis limits as a numpy.float64, and I can't figure out how to convert the numbers to a usable datetime.

import pandas 
from matplotlib import dates
import matplotlib.pyplot as plt
from datetime import datetime
from numpy.random import randn

ts = pandas.Series(randn(10000), index=pandas.date_range('1/1/2000',
    periods=10000, freq='H')) 
ts.plot()
ax = plt.gca()

ax.set_xlim(datetime(2000,1,1))
d1, d2 = ax.get_xlim()
print "%s(%s) to %s(%s)" % (d1, type(d1), d2, type(d2))

print "Using matplotlib: %s" % dates.num2date(d1)
print "Using datetime: %s" % datetime.fromtimestamp(d1)

返回:

262968.0 (<type 'numpy.float64'>) to 272967.0 (<type 'numpy.float64'>)
Using matplotlib: 0720-12-25 00:00:00+00:00
Using datetime: 1970-01-03 19:02:48

根据 pandas时间序列文档,pandas使用numpy. datetime64 dtype.我正在使用熊猫版本"0.9.0".

According to the pandas timeseries docs, pandas uses the numpy.datetime64 dtype. I'm using pandas version '0.9.0'.

我使用get_xlim()代替直接访问熊猫系列,因为当用户在绘图区域中四处移动时,我使用xlim_changed回调执行其他操作.

I am using get_xlim() instead directly accessing the pandas series because I am using the xlim_changed callback to do other things when the user moves around in the plot area.

对于上面的示例,限制是在自大纪元以来的小时中返回的.因此,自大纪元以来,我可以转换为 seconds ,并使用time.gmtime()获取可用的位置,但这仍然感觉不对.

For the above example, the limits are returned in hours since the Epoch. So I can convert to seconds since the Epoch and use time.gmtime() to get somewhere usable, but this still doesn't feel right.

In [66]: d1, d2 = ax.get_xlim()

In [67]: time.gmtime(d1*60*60)
Out[67]: time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=0)  

推荐答案

# First convert to pandas Period
period = pandas.tseries.period.Period(ordinal=int(d1), freq=ax.freq)
# Then convert to pandas timestamp
ts = period.to_timestamp()
# Then convert to date object
dt = ts.to_datetime()

这篇关于从 pandas 时间序列图中的Axes.get_xlim()获取可用日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 03:19