【问题标题】:split dataframe entries at midnight在午夜拆分数据帧条目
【发布时间】:2018-10-24 11:08:08
【问题描述】:

我有一个pandasdataframe,带有StartEnd 数据时间。

df=pd.DataFrame(data=pd.date_range('20100201', periods=10, freq='5h3min'),columns=['Start'])
df.loc[:,'End']=df.loc[:,'Start']+pd.Timedelta(4,'h')

StartEnd 可以预期会相互排序,但连续行之间可能会出现间隙/重叠。

我想创建一个新的数据框,不同之处在于如果行包含午夜(例如,午夜包含在 [Start,End] 中),然后在午夜之前和之后将该行分成两部分 例如:

 Start                 End
0 2010-02-01 00:00:00 2010-02-01 04:00:00
1 2010-02-01 05:03:00 2010-02-01 09:03:00
2 2010-02-01 10:06:00 2010-02-01 14:06:00
3 2010-02-01 15:09:00 2010-02-01 19:09:00
4 2010-02-01 20:12:00 2010-02-02 00:12:00
5 2010-02-02 01:15:00 2010-02-02 05:15:00

应该是

Start                 End
    0 2010-02-01 00:00:00 2010-02-01 04:00:00
    1 2010-02-01 05:03:00 2010-02-01 09:03:00
    2 2010-02-01 10:06:00 2010-02-01 14:06:00
    3 2010-02-01 15:09:00 2010-02-01 19:09:00
    -----------------------------------------
    4 2010-02-01 20:12:00 2010-02-01 23:59:00
    5 2010-02-02 00:00:00 2010-02-02 00:12:00
    -----------------------------------------
    6 2010-02-02 01:15:00 2010-02-02 05:15:00

【问题讨论】:

  • 午夜是什么意思
  • 00:00 基本上是 datetime.min.time()

标签: python pandas datetime dataframe


【解决方案1】:

您可以连接新对的 DataFrame,然后删除旧对。

首先找到分裂:

splits = df[df.End.dt.date > df.Start.dt.date].copy()

现在连接和删除:

>>> pd.concat([
    df,
    pd.DataFrame({
        'Start': list(splits.Start) + list(splits.End.dt.floor(freq='1D')),
        'End': list(splits.Start.dt.ceil(freq='1D')) + list(splits.End)})
]).drop(splits.index).sort_values(by='Start')
    End Start
0   2010-02-01 04:00:00 2010-02-01 00:00:00
1   2010-02-01 09:03:00 2010-02-01 05:03:00
2   2010-02-01 14:06:00 2010-02-01 10:06:00
3   2010-02-01 19:09:00 2010-02-01 15:09:00
0   2010-02-02 00:00:00 2010-02-01 20:12:00
2   2010-02-02 00:12:00 2010-02-02 00:00:00
5   2010-02-02 05:15:00 2010-02-02 01:15:00
6   2010-02-02 10:18:00 2010-02-02 06:18:00
7   2010-02-02 15:21:00 2010-02-02 11:21:00
8   2010-02-02 20:24:00 2010-02-02 16:24:00
1   2010-02-03 00:00:00 2010-02-02 21:27:00
3   2010-02-03 01:27:00 2010-02-03 00:00:00

【讨论】:

  • 考虑使用 DataFrame 的 columns=['Start', 'End'] 设置列顺序并在末尾重置索引。此外,我们缺少 23:59:59 的一秒不同端点。
  • @Parfait 感谢 cmets - 我会在电脑旁编辑它。
  • 我喜欢它。当 nrows 很大并且时间分辨率很高时,它是如何扩展的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 2016-07-28
  • 2016-01-13
  • 2015-09-24
  • 2021-09-23
相关资源
最近更新 更多