【问题标题】:Split DataFrame rows by DateTime in pandas在 Pandas 中按 DateTime 拆分 DataFrame 行
【发布时间】:2017-10-11 20:06:02
【问题描述】:

我有一个包含如下事件的 DataFrame:

location  start_time   end_time     some_value1   some_value2
LECP      00:00        01:30        25            nice info
LECP      02:00        04:00        10            other info
LECS      02:00        03:00         5            lorem
LIPM      02:55        03:15         9            ipsum

我想拆分行以便获得1 hour 的最大间隔,例如如果一个事件的持续时间为01:30,我想得到一行长度为01:00 和另一行00:30。如果一个事件的长度为02:30,我想得到三行。如果一个事件的持续时间为一小时或更短,它应该只是一排。像这样:

location  start_time   end_time   some_value1   some_value2
LECP      00:00        01:00      25            nice info
LECP      01:00        01:30      25            nice info

LECP      02:00        03:00      10            other info
LECP      03:00        04:00      10            other info

LECS      02:00        03:00       5            lorem
LIPM      02:55        03:15       9            ipsum

余数在开头还是结尾都没有关系。只要没有行的持续时间超过 1 小时,持续时间是否平均分配给行甚至都没有关系。

我尝试了什么: - 通读Time Series / Date functionality 却什么都不懂 - 搜索 StackOverflow。

【问题讨论】:

  • 这是因为这些是独立的事件。多个事件可能发生在相同或不同的地点、相同或不同的时间
  • 呃……对不起。我的问题是在您的预期结果中,第二条记录是否应该从 01:00 而不是 00:00 开始?
  • 我的错。是的,你的解释是正确的。编辑了 OP。

标签: python pandas dataframe time-series


【解决方案1】:

我调整了this 答案以实现每小时而不是每天的拆分。此代码在 WHIL 循环中工作,因此只要存在持续时间仍然 > 1 小时的行,它就会重新迭代。

mytimedelta = pd.Timedelta('1 hour')

#create boolean mask
split_rows = (dfob['duration'] > mytimedelta)    

while split_rows.any():
    #get new rows to append and adjust start time to 1 hour later.
    new_rows = dfob[split_rows].copy()
    new_rows['start'] = new_rows['start'] + mytimedelta

    #update the end time of old rows
    dfob.loc[split_rows, 'end'] = dfob.loc[split_rows, 'start'] + \
        pd.DateOffset(hours=1, seconds=-1)
    dfob = dfob.append(new_rows)

    #update the duration of all rows
    dfob['duration'] = dfob['end'] - dfob['start']

    #create an updated boolean mask
    split_rows = (dfob['duration'] > mytimedelta)

#when job is done:
dfob.sort_index().reset_index(drop=True)
dfob['duration'] = dfob['end'] - dfob['start']    

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2015-04-11
    • 1970-01-01
    • 2019-04-22
    相关资源
    最近更新 更多