关于Pandas时间重采样和绘图的问题



我是Python和Pandas的新手。我正在尝试生成一个条形图,显示每天最后一个样本之间的差异。如果我的方法不对,请告诉我。

样本启动数据集

DateTime         Data1       Data2
0   2019-11-10 21:05:12  1.000000e-08      0.000000
1   2019-11-10 21:05:26  1.000000e-08      0.000000
2   2019-11-10 21:13:28  1.000000e-08      0.000000
3   2019-11-10 21:20:17  1.000000e-08      0.000000
4   2019-11-10 21:29:50  1.000000e-08      0.000000
..                  ...           ...           ...
191 2019-11-13 10:05:31  4.918000e-05      0.000004
192 2019-11-13 10:15:32  4.918000e-05      0.000004
193 2019-11-13 10:25:33  4.918000e-05      0.000004
194 2019-11-13 10:35:34  4.918000e-05      0.000004
195 2019-11-13 10:45:35  4.918000e-05      0.000004

这给了我每天的最后一个条目,但它在新行上有一个额外的列,名称相同"DateTime"。当我绘制这个图时,x轴使用的是"DateTime",时间还在其中。我想使用只有日期的列。

res = pd.DataFrame()
res = df.resample('D', on='DateTime').last()
res.plot(kind='bar', x='DateTime')
plt.tight_layout()
plt.show()
print(res)
打印结果
DateTime         Data1         Data2
DateTime                                                  
2019-11-10 2019-11-10 22:00:14  1.000000e-08  0.000000e+00
2019-11-11 2019-11-11 22:31:05  8.460000e-06  1.100000e-07
2019-11-12 2019-11-12 23:13:15  3.718000e-05  3.240000e-06
2019-11-13 2019-11-13 10:25:33  4.918000e-05  4.010000e-06

与前一天相比,这给了我德尔塔。但它仍然有两个同名的列。当我尝试绘制它时,它使用了"DateTime"列,该列有"1天00:30:51",我需要另一列。

res2 = pd.DataFrame()
res2 = res.diff()
res2.drop(res2.index[0], inplace=True)
res2.plot(kind='bar', x='DateTime')
plt.tight_layout()
plt.show()
print(res2)
打印结果
DateTime     Data1         Data2
DateTime                                          
2019-11-11 1 days 00:30:51  0.000008  1.100000e-07
2019-11-12 1 days 00:42:10  0.000029  3.130000e-06
2019-11-13 0 days 11:12:18  0.000012  7.700000e-07

谁能解释一下发生了什么,以及我如何才能得到我需要的条形图吗?

Quang,感谢您的帮助。以下是我正在使用的代码。

res = pd.DataFrame()
res = df.set_index('DateTime').resample('D').last()
res.plot(kind='bar')
plt.tight_layout()
plt.show()
print(res)
res2 = pd.DataFrame()
res2 = res.diff()
res2.drop(res2.index[0], inplace=True)
ax = res2.plot(kind='bar', rot=20)
f = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S').strftime('%b %d')
ax.set_xticklabels([ f(x.get_text()) for x in ax.get_xticklabels()])
plt.tight_layout()
plt.show()
print(res2)

最新更新