【问题标题】:Getting hour and minute out of a numpy array that encodes time从编码时间的numpy数组中获取小时和分钟
【发布时间】:2014-05-31 23:42:28
【问题描述】:

我有一个对时间进行编码的大型 numpy 数组。假设我们有这样的事情:

from pandas import DataFrame
t = {'time': ['08:35', '08:38', '13:42', '13:46']}
df = DataFrame(t)

import numpy as np
time_array = np.array(df.time)
print time_array

输出:

['08:35' '08:38' '13:42' '13:46']

有没有一种有效的方法可以从 time_array 中单独获取小时和分钟?

当然这可以在循环中完成:

for i in range(len(time_array)):
    print np.fromstring(time_array[i], dtype=int, sep=":")

输出:

[ 8 35]
[ 8 38]
[13 42]
[13 46]

但我正在寻找一种“更快”的矢量化方式,如果有的话。

编辑:

我已经为解决方案计时(参见下面的代码)。

def foo(array):
    for i in range(len(array)):
        array[i] = np.fromstring(array[i], dtype=int, sep=':')

%timeit foo(time_array)

输出:1 个循环,最好的 3 个:每个循环 3.02 秒

Paul H 的解决方案 1:

def foo2(df):
    df['hour'] = df['time'].apply(lambda x: int(x.split(':')[0]))
    df['minute'] = df['time'].apply(lambda x: int(x.split(':')[1]))

%timeit foo2(df)

输出:1 个循环,最好的 3 个:每个循环 4.31 秒

Paul H 的解决方案 2:

import time
def foo3(df):
    df['hour'] = df['time'].apply(lambda x: time.strptime(x, '%H:%M').tm_hour)
    df['minute'] = df['time'].apply(lambda x: time.strptime(x, '%H:%M').tm_min)

%timeit foo3(df)

输出:1 个循环,最好的 3 个:每个循环 42.1 秒

【问题讨论】:

    标签: python-2.7 numpy pandas


    【解决方案1】:

    我会在 pandas 多呆一会儿:

    from pandas import DataFrame
    t = {'time': ['08:35', '08:38', '13:42', '13:46']}
    df = DataFrame(t)
    df['hour'] = df['time'].apply(lambda x: int(x.split(':')[0]))
    df['minute'] = df['time'].apply(lambda x: int(x.split(':')[1]))
    print(df)
    
        time  hour  minute
    0  08:35     8      35
    1  08:38     8      38
    2  13:42    13      42
    3  13:46    13      46
    

    然后您可以通过df['hour'].values 获取小时数组。

    编辑:

    只是为了笑,你也可以这样做:

    import time
    df['hour'] = df.timestring.apply(lambda x: time.strptime(x, '%H:%M').tm_hour)
    df['minute'] = df.timestring.apply(lambda x: time.strptime(x, '%H:%M').tm_min)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 2012-07-04
      • 1970-01-01
      • 2018-07-29
      相关资源
      最近更新 更多