检测日期集中(python中的列表)

时间:2019-07-15 19:51:10

标签: python

我在Python中有一个名为array_my_date的列表,我需要检测日期的集中程度。

条件是:

  • 浓度定义为即将到来的3个以上日期。
  • 如果日期在25天之内,则视为接近日期
array_my_date = []
array_my_date.append(pd.to_datetime('2013-06-24 00:00:00'))
array_my_date.append(pd.to_datetime('2013-06-26 00:00:00'))
array_my_date.append(pd.to_datetime('2013-06-27 00:00:00'))
array_my_date.append(pd.to_datetime('2013-06-29 00:00:00'))
array_my_date.append(pd.to_datetime('2013-07-01 00:00:00'))
array_my_date.append(pd.to_datetime('2013-07-03 00:00:00'))
array_my_date.append(pd.to_datetime('2013-07-04 00:00:00'))
array_my_date.append(pd.to_datetime('2013-07-06 00:00:00'))
array_my_date.append(pd.to_datetime('2013-07-07 00:00:00'))
array_my_date.append(pd.to_datetime('2013-07-08 00:00:00'))

array_my_date.append(pd.to_datetime('2015-03-01 00:00:00'))
array_my_date.append(pd.to_datetime('2015-03-04 00:00:00'))

array_my_date.append(pd.to_datetime('2017-09-29 00:00:00'))
array_my_date.append(pd.to_datetime('2017-10-02 00:00:00'))
array_my_date.append(pd.to_datetime('2017-10-06 00:00:00'))
array_my_date.append(pd.to_datetime('2017-10-07 00:00:00'))
array_my_date.append(pd.to_datetime('2017-10-08 00:00:00'))
array_my_date.append(pd.to_datetime('2017-10-09 00:00:00'))

array_my_date.append(pd.to_datetime('2018-12-09 00:00:00'))

预期输出是第一次集中注意力的日期。那就是:

[Timestamp('2013-06-24 00:00:00'), Timestamp('2017-09-29 00:00:00')]

1 个答案:

答案 0 :(得分:0)

首先,确保日期列表已排序:

dates = sorted(array_my_date)

然后,逐步建立浓度列表:

concentrations = [[dates[0]]]                        # initialize our memory with the first date
for date in dates[1:]:                               # iterate through the rest of the dates
    last_date = concentrations[-1][-1]               # look at the last date we added
    if (date - last_date) <= pd.Timedelta(days=25):  # is it close enough to be in the same group?
        concentrations[-1].append(date)              # if so, then put it in the same group
    else:                                            # otherwise,
        concentrations.append([date])                # make a new group with it at the head

这将产生以下内容:

>>> pprint.pprint(concentrations)
[[Timestamp('2013-06-24 00:00:00'),
  Timestamp('2013-06-26 00:00:00'),
  Timestamp('2013-06-27 00:00:00'),
  Timestamp('2013-06-29 00:00:00'),
  Timestamp('2013-07-01 00:00:00'),
  Timestamp('2013-07-03 00:00:00'),
  Timestamp('2013-07-04 00:00:00'),
  Timestamp('2013-07-06 00:00:00'),
  Timestamp('2013-07-07 00:00:00'),
  Timestamp('2013-07-08 00:00:00')],
 [Timestamp('2015-03-01 00:00:00'), Timestamp('2015-03-04 00:00:00')],
 [Timestamp('2017-09-29 00:00:00'),
  Timestamp('2017-10-02 00:00:00'),
  Timestamp('2017-10-06 00:00:00'),
  Timestamp('2017-10-07 00:00:00'),
  Timestamp('2017-10-08 00:00:00'),
  Timestamp('2017-10-09 00:00:00')],
 [Timestamp('2018-12-09 00:00:00')]]

然后您可以通过执行类似的操作来获取每个时间段中最早的日期

earliest_of_each = [group[0] for group in concentrations]