【问题标题】:Accessing the datetime.time (00:00 - 23:59) format in a numeric data type以数字数据类型访问 datetime.time (00:00 - 23:59) 格式
【发布时间】:2019-06-28 21:40:54
【问题描述】:

我有一个 24 小时的平均数据,根据 00:00 - 23:59 以 1 分钟的间隔编制索引。这导致每分钟对应 1440 个数据点。我想将这些时间戳映射到它们的数字索引,范围从 0-1440(因为一整天有 1440 分钟)。

例如,00:00 ->0、00:01->1、00:02->2 ...23:58->1339、23:59->1440

时间 = 01:11 dtype:datetime.time
time.func()
71

我尝试在 pandas 中搜索 datetime.time 格式是否有任何此类功能。但是,我找不到任何东西。

如果 pandas 中没有内置功能,另一种方法可能是编写一个将特定 datetime.time 映射到索引 (0-1440) 的函数。

【问题讨论】:

  • 如果00:00 是索引0,那么23:59 必须是1439。应该这样做:time.hour * 60 + time.minute

标签: python pandas time


【解决方案1】:

看看这是不是你想要的:

import pandas as pd
df = pd.DataFrame(['23:57', '10:39', '4:03'], columns=['Time'])

这个数据框看起来像:

    Time
0  23:57
1  10:39
2   4:03

然后我们可以在我们的列上应用这个函数:

df['Time'].apply(lambda x: int(pd.to_timedelta(pd.to_datetime(x, format='%H:%M').strftime('%H:%M:00'), unit='m').total_seconds()/60))

其中的输出是:

0    1437
1     639
2     243
Name: Time, dtype: int64

这里我们使用 apply 将相同的函数应用于列的所有元素。

  1. 转换为日期时间格式(这里我使用 '%H:%M' 指定格式,以确保我们明确地将时间转换为小时和分钟。
  2. 通过使用 strftime 添加 ':00' 来使用额外的秒元素格式化时间,这是因为 pd.to_timedelta 需要 'hh:mm:ss' 格式的时间
  3. 然后我们得到 timedelta 的 total_seconds() 并除以 60 得到分钟
  4. 转换为整数以获得最终格式。

【讨论】:

    【解决方案2】:

    pandas 没有原生 time dtype,但它确实有 timedelta:

    In [11]: t = dt.time(10, 15)
    
    In [12]: t.hour * 60 + t.minute  # total minutes (this may suffice!)
    Out[12]: 615
    
    In [13]: pd.to_timedelta((t.hour * 60 + t.minute), unit='m')
    Out[13]: Timedelta('0 days 10:15:00')
    

    注意:您也许可以从一开始就从 timedelta 开始工作(无论是在解析中还是通过计算):

    In [14]: pd.to_timedelta('10:15:00')
    Out[14]: Timedelta('0 days 10:15:00')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-04
      • 2014-08-09
      • 2021-07-05
      • 1970-01-01
      • 2020-04-20
      • 2015-03-21
      • 2021-02-08
      • 1970-01-01
      相关资源
      最近更新 更多