【问题标题】:Counting Cumulative Occurrences and Plotting Over Time in Pandas在 Pandas 中计算累积发生次数并随时间绘制
【发布时间】:2019-12-10 07:35:33
【问题描述】:

给定一个示例数据框,如下所示:

Time              Type
2019-12-09 04:50  Exists
2019-12-08 01:20  Does Not Exist
2019-12-08 03:32  Exists
2019-12-07 01:15  APPLES
2019-12-05 04:13  Does Not Exist

我想累计计算“存在”和“不存在”的出现次数,而不是“APPLES”的出现次数,并绘制这两个值与时间的关系。我已经创建了Occurrences,如下图,但是时间不是升序的。

  1. 如何将时间更改为升序,然后仅在散点图中仅绘制“存在”和“不存在”?

谢谢。

import pandas as pd

my_cols = ["Time","Type"]
df = pd.read_csv('occurrences.txt',names = my_cols,sep=';')
df['Time'] = pd.to_datetime(df['Time'])
df.set_index('Time',inplace=True)
df['Occurrence'] = df.groupby("Type").cumcount()

【问题讨论】:

  • 剧情应该是怎样的?两条单独的行,一条代表存在,一条代表不存在?
  • 是的,这就是我想要的:X 轴上的时间,Y 轴上的累积出现次数。

标签: python pandas


【解决方案1】:

先过滤你的df,然后sort_values:

new = df.loc[df['Type'].ne("APPLES")].sort_values(["Type","Time"])

new["occurance"] = new.groupby("Type").cumcount()
new.set_index("Time").groupby('Type')['occurance'].plot(legend=True)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多