【问题标题】:Plotting using Pandas and datetime format使用 Pandas 和日期时间格式绘图
【发布时间】:2019-02-15 09:03:15
【问题描述】:

我有一个只有两列的数据框,即 Date 和 ClosingPrice。我正在尝试使用 df.plot() 绘制它们,但不断收到此错误:

ValueError:视图限制最小值 -36785.37852 小于 1 并且是无效的 Matplotlib 日期值。如果您将非日期时间值传递给具有日期时间单位的轴,这通常会发生

我从 matplotlib 中找到了关于此的文档,但其中说明了如何确保格式为日期时间。这是我必须确保格式为日期时间的代码,并在尝试绘制之前打印每列的数据类型。

df.Date = pd.to_datetime(df.Date)

print(df['ClosingPrice'].dtypes)
print(df['Date'].dtypes)

这些打印语句的输出是:

float64 日期时间64[ns]

我不确定问题出在哪里,因为我在绘图之前验证了数据类型。这也是数据集的前几行的样子:

Date ClosingPrice 0 2013-09-10 64.7010 1 2013-09-11 61.1784 2 2013-09-12 61.8298 3 2013-09-13 60.8108 4 2013-09-16 58.8776 5 2013-09-17 59.5577 6 2013-09-18 60.7821 7 2013-09-19 61.7788 任何帮助表示赞赏。

【问题讨论】:

  • 我在绘制这个时没有问题。你能发布导致错误的代码行吗?
  • 它发生在具有 df.plot() 的行上。没有其他东西在线上。如果您愿意,我可以提供更多代码吗?

标签: python pandas datetime matplotlib


【解决方案1】:

EDIT 2 看到更多人来到这里。为了让新人了解 python,您应该首先导入 pandas 以使下面的代码起作用:

import pandas as pd

编辑 1:(简短的快速回答)

如果³您不想删除原始索引(在阅读下面的原始和长答案后这是有道理的),您可以:

df[['Date','ClosingPrice']].plot('Date', figsize=(15,8))

原始而冗长的答案:

先尝试将索引设置为日期时间列:

df.set_index('Date', inplace=True, drop=True)

为了确定,尝试设置 index dtype(编辑:这可能不需要像以前那样):

df.index = pd.to_datetime(df.index)

然后画出来

df.plot()

如果这解决了问题,那是因为当您使用来自 DataFrame 对象的.plot() 时,X 轴将自动成为 DataFrame 的索引。

如果²您的 DataFrame 有一个 Datetimeindex 和 2 个其他列(例如 ['Currency','pct_change_1'])并且您只想绘制其中一个(也许是 pct_change_1),您可以:

# single [ ] transforms the column into series, double [[ ]] into DataFrame
df[['pct_change_1']].plot(figsize=(15,8)) 

figsize=(15,8) 您正在设置绘图的大小(width, height)

【讨论】:

  • 所以我添加了第一行,但它似乎正在删除我想说的数据。我在您推荐的行之后打印数据框,它显示为无。伴随着这个错误:df.plot() AttributeError: 'NoneType' object has no attribute 'plot'
  • 我不确定 pandas 是否改变了某些东西,但我将您的第一行更改为 df = df.set_index('Date')。它工作并绘制得很好。感谢您的帮助。我刚刚尝试了您的最后一次编辑,它也有效。
  • 哦,因为我声明了df =,所以不需要inplace=True。如果您只是输入df.set_index('Date', inplace=True),它会。要么是那个,要么是因为我们正在运行不同的 python 版本(我是最新的)。
  • 你上次的编辑对我有用 df[['Date','ClosingPrice']].plot('Date', figsize=(15,8))
  • 很高兴知道,可能是因为您说哪一列必须是“.plot()”处的 X 轴,所以它没有考虑 DF 的索引。
【解决方案2】:

这是一个简单的解决方案:

  my_dict = {'Date':['2013-09-10', '2013-09-11', '2013-09-12', '2013-09-13', '2013-09-16', '2013-09-17', '2013-09-18',
     '2013-09-19'], 'ClosingPrice': [ 64.7010, 61.1784, 61.8298, 60.8108, 58.8776, 59.5577, 60.7821, 61.7788]}

  df = pd.DataFrame(my_dict)
  df.set_index('Date', inplace=True)
  df.plot()

【讨论】:

  • 您好,这是行不通的,因为您没有就地设置索引 (df.set_index('Date', inplace=True)) 或将 df 替换为新的 df 为新的 set_index (df = df.set_index('Date'))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 2015-12-23
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多