【问题标题】:Number of concurrent processes in PandasPandas 中的并发进程数
【发布时间】:2018-07-04 11:26:27
【问题描述】:

给定一个 Pandas 数据框,它表示某些程序何时开始工作以及何时完成(即单行 - 单个程序):

      starts            finishes
2018-01-01 12:00    2018-01-01 15:00
2018-01-01 16:00    2018-01-01 20:00
2018-01-01 16:30    2018-01-01 20:00
2018-01-01 17:00    2018-01-01 21:00
                ...

我需要计算表中表示的每次并发程序数。上表变为下一个:

      time             number_of_conc_progs
2018-01-01 12:00                 1
2018-01-01 15:00                 0
2018-01-01 16:00                 1
2018-01-01 16:30                 2               
2018-01-01 17:00                 3
2018-01-01 20:00                 1                
2018-01-01 21:00                 0 
                     ...

如果一个程序在 12:00 开始(例如)并且当前进程数是 n,那么在 12:00 这个数字的值是 n +1.

如果一个程序在 12:00 结束(例如)并且当前进程数是 n,那么在 12:00 这个数字的值是 n -1.

【问题讨论】:

  • 你能展示你到目前为止所做的事情吗?
  • 我什至不知道从哪里开始)
  • 我明白了。等 5 分钟,我给你你需要的代码 ;)

标签: python pandas dataframe time-series


【解决方案1】:
# creation of the dataframe
df = pd.DataFrame([
    ["2018-01-01 12:00", "2018-01-01 15:00"], 
    ["2018-01-01 16:00", "2018-01-01 20:00"], 
    ["2018-01-01 16:30", "2018-01-01 20:00"], 
    ["2018-01-01 17:00", "2018-01-01 21:00"]])
df.columns = ["starts", "finishes"]

# number of progs increases of 1 for start times
starts = pd.DataFrame()
starts["time"] = df.starts
starts["number_of_conc_progs"] = 1

# number of progs decreases of 1 for finishes times
finishes = pd.DataFrame()
finishes["time"] = df.finishes
finishes["number_of_conc_progs"] = -1

# then I merge the starts and the finishes dataframes
result = pd.DataFrame()
result = pd.concat([starts,finishes])
# I sort the time values
result = result.sort_values(by=['time'])
# If there is several starts or finishes at the same time, I sum them
result = result.groupby(['time']).sum()
# I do a cumulation sum to get the actual number of progs running
result.number_of_conc_progs = result.number_of_conc_progs.cumsum()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2010-11-10
    • 1970-01-01
    • 2017-06-17
    相关资源
    最近更新 更多