我正在尝试绘制一个简单的时间序列。这是我的代码:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
%matplotlib inline
df = pd.read_csv("sample.csv", parse_dates=['t'])
df[['sq', 'iq', 'rq']] = df[['sq', 'iq', 'rq']].apply(pd.to_numeric, errors='coerce')
df = df.fillna(0)
df.set_index('t')
这是输出的一部分:
df[['t','sq']].plot()
plt.show()
如您所见,上图中的x轴不是我想要显示的日期。当我更改下面的绘图调用时,我得到以下乱码图,虽然x轴现在是正确的。
df[['t','sq']].plot(x = 't')
plt.show()
关于我做错的任何提示?如果您需要有关该问题的更多信息,请发表评论并告诉我们。提前谢谢。
答案 0 :(得分:1)
我认为你的问题是虽然你已经解析了t列,但它不是日期时间类型。请尝试以下方法:
# Set t to date-time and then to index
df['t'] = pd.to_datetime(df['t'])
df.set_index('t', inplace=True)
阅读你的评论和你添加的答案有人可能会得出结论,这种问题只能通过在pd.read_csv()中指定解析器来解决。所以这证明我的解决方案原则上是有效的。查看您发布的问题,代码的另一个问题是您指定plot命令的方式。一旦t成为索引,您只需要为plot命令选择除t之外的列。
import pandas as pd
import matplotlib.pyplot as plt
# Read data from file
df = pd.read_csv('C:\\datetime.csv', parse_dates=['Date'])
# Convert Date to date-time and set as index
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
df.plot(marker='D')
plt.xlabel('Date')
plt.ylabel('Number of Visitors')
plt.show()
df
Out[37]:
Date Adults Children Seniors
0 2018-01-05 309 240 296
1 2018-01-06 261 296 308
2 2018-01-07 273 249 338
3 2018-01-08 311 250 244
4 2018-01-08 272 234 307
df
Out[39]:
Adults Children Seniors
Date
2018-01-05 309 240 296
2018-01-06 261 296 308
2018-01-07 273 249 338
2018-01-08 311 250 244
2018-01-08 272 234 307
答案 1 :(得分:0)
正如上面的答案所指出的那样,这个问题被证明是错误的日期解析。但是,它的解决方案是将date_parser
传递给read_csv
方法调用:
from datetime import datetime as dt
dtm = lambda x: dt.strptime(str(x), "%Y-%m-%d")
df = pd.read_csv("sample.csv", parse_dates=['t'], infer_datetime_format = True, date_parser= dtm)