Pandas的日期被错误地标在月初

2024-04-20 01:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我在熊猫中有一个时间序列,日期在月底:

import pandas as pd
s = pd.Series({
    '2018-04-30':     0,
    '2018-05-31':     1,
    '2018-06-30':     0,
    '2018-07-31':    1,
    '2018-08-31':    0,
    '2018-09-30':    1,
})
s.index = pd.to_datetime(s.index)

当我用matplotlib绘制这个图时,我得到了我期望的结果,点在月底,线在2018年5月之前开始:

import matplotlib.pyplot as plt
plt.plot(s)

Matplotlib graph

但熊猫的原生绘图功能会在月初绘制点:

s.plot()

Pandas graph

我想也许这只是熊猫将“4月30日”标记为“4月”,但事实似乎并非如此:

s2 = pd.Series([0.2, 0.7], index=pd.date_range('2018-05-01', '2018-05-02'))
s.plot()
s2.plot()

Pandas plot with first-of-month also plotted

这是熊猫里的虫子还是我做错了什么?你知道吗


Tags: toimportpandasdatetimeindexplotmatplotlibas
1条回答
网友
1楼 · 发布于 2024-04-20 01:22:48

这似乎是熊猫身上的一种虫子。要获得与matplotlib相同的结果,可以始终使用x_compat=True。这样还允许使用matplotlib.dates格式化程序和定位器。你知道吗

s = pandas.Series(...)
s.plot(x_compat=True)

相关问题 更多 >