简体   繁体   English

为什么 Parse_Dates 在 Python 中给我错误的结果?

[英]Why does Parse_Dates give me the wrong results in Python?

I am trying to plot a Time Series Graph with Matplotlib.我正在尝试使用 Matplotlib 绘制时间序列图。 I have a 2 column CSV file, with dates and closing prices of stocks (Dates are given in the format: '31/07/2020'.我有一个 2 列 CSV 文件,其中包含股票的日期和收盘价(日期的格式为:“31/07/2020”。

First, I parse my dates column to make it a datetime list.首先,我解析我的日期列以使其成为日期时间列表。 Then I plot my data, through the following code:然后我通过以下代码绘制我的数据:

data = pd.read_csv('data.csv', parse_dates=['DATE'])

date = data['DATE']
stock1 = data['GEN_ELECTRIC']
stock2 = data['NETFLIX']

plt.figure()
plt.plot(date, stock1)
plt.savefig('Wrong.png')

I get the graph called 'Wrong.png' attached.我附上了名为“Wrong.png”的图表。 If I leave out the parse_dates, I get a correct graph, called 'Correct.png'.如果我省略 parse_dates,我会得到一个正确的图形,称为“Correct.png”。

My question is, the 'Wrong.png' has x-ticks with only years and Python knows its talking about dates.我的问题是,'Wrong.png' 的 x-ticks 只有年份,而 Python 知道它在谈论日期。 With the correct version, this is not the case.使用正确的版本,情况并非如此。 Furthermore, the 'correct' version also shows the month and day, which is not necessary.此外,“正确”版本还显示月份和日期,这是不必要的。 Does anyone know, why I am getting a wrong graph?有谁知道,为什么我得到一个错误的图表? How would I go about fixing this?我将如何解决这个问题?

PS.附注。 Don't mind the overlapping x-axis in the correct.png, I can fix that with plt.locator.不要介意在正确的.png 中重叠的 x 轴,我可以用 plt.locator 解决这个问题。

Any help would be appreciated.任何帮助,将不胜感激。 Thanks in advance!提前致谢!

错误的

正确的

parse_dates default format is not DD/MM/YYYY as in european style. parse_dates默认格式不是欧洲风格的 DD/MM/YYYY。 If your first row is let's say 1/7/2020, it may interpret it as 7 of January.如果您的第一行是 1/7/2020,它可能会将其解释为 1 月 7 日。 Later on, when encountered on 30/07/2020, parse_dates will encounter a problem and returns an object data type.稍后,当遇到 30/07/2020 时, parse_dates 会遇到问题并返回对象数据类型。 To correctly use parse_dates, add the dayfirst=True attribute to read_csv.要正确使用 parse_dates,请将dayfirst=True属性添加到 read_csv。 It's the right way to declare DD/MM format.这是声明 DD/MM 格式的正确方法。 Then matplotlib should handle the rest fine然后 matplotlib 应该可以很好地处理其余部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM