首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python:打印使用`period_range` (pandas)创建的数据时出错

Python:打印使用`period_range` (pandas)创建的数据时出错
EN

Stack Overflow用户
提问于 2018-07-13 06:56:19
回答 1查看 1.5K关注 0票数 2

我在绘制使用pandas date_rangeperiod_range创建的时间序列数据时遇到问题。前者行得通,但后者不行。要说明该问题,请考虑以下内容

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# random numbers
N = 100
z = np.random.randn(N)
ts = pd.DataFrame({'Y': z, 'X': np.cumsum(z)})

# 'date_range' is used
month_date = pd.date_range('1978-02', periods=N, freq='M')
df_date = ts.set_index(month_date)

# 'period_range' is used
month_period = pd.period_range('1978-02', periods=N, freq='M')
df_period = ts.set_index(month_period)

# plot
plt.plot(df_date);plt.show()
plt.plot(df_period);plt.show()

plt.plot(df_date)给出了一个很好的数字,而plt.plot(df_period)生成了以下错误,这是我不理解的:

ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units<Figure size 432x288 with 1 Axes>

这是一个预期的结果吗?这里我漏掉了什么?

BTW、df_date.plot()df_period.plot()都工作得很好,不会造成任何问题。

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-13 07:11:38

两个dateframes的索引类型不同:

print(type(df_date))    # pandas.core.indexes.datetimes.DatetimeIndex
print(type(df_period))  # pandas.core.indexes.period.PeriodIndex

Matplotlib不知道如何绘制PeriodIndex

你可以用convert the PeriodIndex to a DatetimeIndex和plot来代替它

plt.plot(df_period.to_timestamp())
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51315526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档