簡體   English   中英

如何在兩個日期之間添加日期范圍 - Python Pandas

[英]How add date_range between two dates - Python Pandas

我想處理幾天之間的時間重疊。 正如您在我的 df 中看到的,我的開始日期為 2019-10-25,結束日期為 2019-10-27:

begin                       end                          info
2019-10-25 10:39:58.352073  2019-10-25 10:40:06.266782   toto
2019-10-25 16:35:22.485574  2019-10-27 09:50:31.713179   tata <------ HERE
2019-10-27 09:50:31.713179  2019-10-27 09:50:31.713192   titi
2019-10-28 14:04:33.095633  2019-10-28 14:05:07.639344   tete

我想在這兩個日期之間添加盡可能多的時間段(日期 00:00:00;日期 23:59:59.9)並復制數據信息,如下所示:

2019-10-25 16:35:22.485574  2019-10-25 23:59:59.999999   tata
2019-10-26 00:00:00.000000  2019-10-26 23:59:59.999999   tata
2019-10-27 00:00:00.000000  2019-10-27 09:50:31.713179   tata
  • 如果開始日期與結束日期不同,那么 => 計算天數
  • 保留開頭並添加新的結尾“日期 23:59:59.9”
  • 添加新的 date_range 對應的天數
  • 結束並添加新的開始 'date 00:00:00.0'
  • 填寫“信息”

最終的預期結果:

begin                       end                          info
2019-10-25 10:39:58.352073  2019-10-25 10:40:06.266782   toto

2019-10-25 16:35:22.485574  2019-10-25 23:59:59.999999   tata
2019-10-26 00:00:00.000000  2019-10-26 23:59:59.999999   tata
2019-10-27 00:00:00.000000  2019-10-27 09:50:31.713179   tata

2019-10-27 09:50:31.713179  2019-10-27 09:50:31.713192   titi
2019-10-28 14:04:33.095633  2019-10-28 14:05:07.639344   tete

但我不知道如何實現日期范圍,填充信息,添加具體的行數。

謝謝你的時間

假設beginend已經是Timestamp類型:

# Generate a series of Timedeltas for each row
n = (
    (df['end'].dt.normalize() - df['begin'].dt.normalize())
        .apply(lambda d: [pd.Timedelta(days=i) for i in range(d.days+1)])
        .explode()
).rename('n')
df = df.join(n)

# Adjust the begin and end of each row
adjusted_begin = np.max([
    df['begin'],
    df['begin'].dt.normalize() + df['n']
], axis=0)

adjusted_end = np.min([
    df['end'],
    pd.Series(adjusted_begin).dt.normalize() + pd.Timedelta(days=1, milliseconds=-100)
], axis=0)

# Final assembly
df = df.assign(begin_=adjusted_begin, end_=adjusted_end)

結果:

                       begin                        end  info      n                     begin_                       end_
0 2019-10-25 10:39:58.352073 2019-10-25 10:40:06.266782  toto 0 days 2019-10-25 10:39:58.352073 2019-10-25 10:40:06.266782
1 2019-10-25 16:35:22.485574 2019-10-27 09:50:31.713179  tata 0 days 2019-10-25 16:35:22.485574 2019-10-25 23:59:59.900000
1 2019-10-25 16:35:22.485574 2019-10-27 09:50:31.713179  tata 1 days 2019-10-26 00:00:00.000000 2019-10-26 23:59:59.900000
1 2019-10-25 16:35:22.485574 2019-10-27 09:50:31.713179  tata 2 days 2019-10-27 00:00:00.000000 2019-10-27 09:50:31.713179
2 2019-10-27 09:50:31.713179 2019-10-27 09:50:31.713192  titi 0 days 2019-10-27 09:50:31.713179 2019-10-27 09:50:31.713192
3 2019-10-28 14:04:33.095633 2019-10-28 14:05:07.639344  tete 0 days 2019-10-28 14:04:33.095633 2019-10-28 14:05:07.639344

修剪掉不需要的列

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM