如何在python中绘制“历史”数据

问题描述 投票:1回答:2

下午好,

我找不到绘制/绘制历史数据(时间序列)并要求您提供有关我的问题的反馈的方法。

我有一个csv文件,其中包含基于某些条件的pid的历史记录。该文件如下所示:

|2019-12-13 14:00:00| 123456 |
|2019-12-13 14:00:00| 345678 |
|2019-12-13 14:00:20| 123456 |
|2019-12-13 14:00:20| 345678 |
|2019-12-13 14:00:40| 123456 |
|2019-12-13 14:00:40| 345678 |
|2019-12-13 14:00:40| 678123 |
|2019-12-13 14:01:00| 123456 |
|2019-12-13 14:01:00| 678123 |

所以我们有:

  • 从2019-12-13 14:00:00到2019-12-13 14:01:00的PID 123456
  • 从2019-12-13 14:00:00到2019-12-13 14:00:40的pid 345678
  • 从2019-12-13 14:00:40到2019-12-13 14:01:00的pid 678123

[我想在我的时间戳记开始处绘制一个X轴折线图,并在我的pid处绘制一个Y-xis线图,以查看我的时间范围内流程的创建/死亡。

我将从将数据存储在pandas数据框中开始,但是后来我不知道如何前进。

有什么建议可以帮助我继续吗?

提前感谢

python pandas graph
2个回答
2
投票

这就是我要做的:

# for shifting and naming lines
codes, names = df['pid'].factorize()

ax = (df.assign(pid_name=codes)
   .pivot(index='timestamp', columns='pid_name', values='pid')
   .plot()
)

# rename legend
h,l = ax.get_legend_handles_labels()
ax.legend(h, names)

输出:

enter image description here


1
投票

按'pid'分组,然后在组中将时间设置为索引,并将该列重命名为pid的值。然后连接结果数据帧:

  r=[ grp.set_index("time") \
         .assign(pid=idx) \
         .rename(columns={"pid":pid}) \
      for idx,(pid,grp) in enumerate(df.groupby("pid"),1) ]

e.ig.: r[0]                                                                                                                
                     123456
time                       
2019-12-13 14:00:00       1
2019-12-13 14:00:20       1
2019-12-13 14:00:40       1
2019-12-13 14:01:00       1

rslt=pd.concat(r,axis=1).fillna(0).astype(int)                                                                      

                     123456  345678  678123
time                                       
2019-12-13 14:00:00       1       1       0
2019-12-13 14:00:20       1       1       0
2019-12-13 14:00:40       1       1       1
2019-12-13 14:01:00       1       0       1

# from matplotlib import pylab as plt
rslt.plot()                                                                                                          
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.