Python绘制DateTime格式

问题描述

我正在处理一个Twitter数据,我想对其进行绘图以显示一天中发生了多少条Tweet。我使用了groupby函数来计算发生了多少条推文。 date数据类型已经转换为日期时间。看起来大概是这样。

date                  tweet
2020-07-25 12:27:21   2
2020-02-13 10:04:16   4

我尝试了这段代码,但是得到了ValueError: x and y must have same first dimension

fig,ax = plt.subplots()
ax.plot_date(df['date'],df['tweet'])

做到这一点的最佳方法是什么?而且由于我只需要日,月和年格式,是否需要删除小时,分钟和秒?如果是这样,请将其包含在答案中。

解决方法

希望这对您有帮助!

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([['2020-07-25 12:27:21',2],['2020-02-13 10:04:16',4]],columns = ['Date','Tweet'])

df['Date'] = pd.to_datetime(df['Date'],format='%Y-%m-%d %H:%M:%S').dt.strftime('%m/%d/%Y')
df['Date'] = df['Date'].apply(lambda x : ' ' if x=="NaT" else x)

cou = df['Tweet'].values
dat = df['Date'].values

plt.bar(dat,cou)
plt.legend()
plt.xlabel('Date')
plt.ylabel('Count')
plt.show()

enter image description here