【问题标题】:Splitting time by the hour Python按小时划分时间 Python
【发布时间】:2015-07-07 21:16:27
【问题描述】:

我有一个像这样的数据框 df1,其中 starttime 和 endtime 是日期时间对象。

开始时间结束时间

9:08 9:10
9:10 9:35
9:35 9:55
9:55 10:10
10:10 10:20

如果 endtime.hour 与 starttime.hour 不同,我想这样分割时间

开始时间结束时间

9:08 9:10

9:10 9:55

9:55 10:00

10:00 10:10

10:10 10:20

本质上是在现有数据框 df1 中插入一行。我看过很多例子,但还没有弄清楚如何做到这一点。如果我的问题不清楚,请告诉我。

谢谢

【问题讨论】:

  • 您卡在哪一部分?转换为日期时间并提取小时,或将一行插入数据框中?我想你会想写一两个辅助函数,你可能需要重置索引。

标签: python-2.7 datetime pandas


【解决方案1】:

这就是你想要的......

# load your data into a DataFrame
data="""StartTime EndTime
9:08 9:10
9:10 9:35
9:35 9:55
9:55 10:10
10:10 10:20
"""
from StringIO import StringIO # import from io for Python 3
df = pd.read_csv(StringIO(data), header=0, sep=' ', index_col=None)

# convert strings to Pandas Timestamps (we will ignore the date bit) ...
import datetime as dt
df.StartTime = [dt.datetime.strptime(x, '%H:%M') for x in df.StartTime]
df.EndTime = [dt.datetime.strptime(x, '%H:%M') for x in df.EndTime]

# assumption - all intervals are less than 60 minutes
#            - ie. no multi-hour intervals

# add rows
dfa = df[df.StartTime.dt.hour != df.EndTime.dt.hour].copy()
dfa.EndTime = [dt.datetime.strptime(str(x), '%H') for x in dfa.EndTime.dt.hour]

# play with the start hour ...
df.StartTime = df.StartTime.where(df.StartTime.dt.hour == df.EndTime.dt.hour,
    other = [dt.datetime.strptime(str(x), '%H') for x in df.EndTime.dt.hour])

# bring back together and sort
df = pd.concat([df, dfa], axis=0) #top/bottom
df = df.sort('StartTime')

# convert the Timestamps to times for easy reading
df.StartTime = [x.time() for x in df.StartTime]
df.EndTime = [x.time() for x in df.EndTime]

和产量

In [40]: df
Out[40]: 
  StartTime   EndTime
0  09:08:00  09:10:00
1  09:10:00  09:35:00
2  09:35:00  09:55:00
3  09:55:00  10:00:00
3  10:00:00  10:10:00
4  10:10:00  10:20:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 2022-10-06
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    相关资源
    最近更新 更多