从字符串(或DataFrame对象)中提取时间数据的更有效方法

问题描述 投票:0回答:2

我正在独自学习Python,这是我在这里的第一个问题。总是能够找到已经回答的所有需求。终于有了一些我认为值得提出的问题。这只是更具体的任务,我什至不知道要搜索什么。

我们的其中一台机器正在生成一个日志文件,在将其加载到DataFrame之后并能够使用之前,需要进行大量清理。无需过多讨论,日志文件包含非常奇怪的格式的时间记录。它是由分钟,秒和毫秒组成的。我可以使用下面显示的功能将其解码为秒(然后将其转换为另一种时间格式)。它工作正常,但是这是一个非常基本的功能,带有许多ifmetets。

我的目标是将其重写为更不业余的外观,但是日志时间格式至少对我来说具有一些挑战性的限制。而且,即使单位是相同的两个字母的组合也无济于事。

以下是所有可能的时间记录组合的样本:

test1 = 'T#3853m10s575ms'   # 231190.575 [seconds]
test2 = 'T#10s575ms'        # 10.575
test3 = 'T#3853m575ms'      # 231180.575
test4 = 'T#575ms'           # 0.575
test5 = 'T#3853m10s'        # 231190
test6 = 'T#10s'             # 10
test7 = 'T#3853m'           # 231180
test8 = 'T#0ms'             # 0

我试图以正则表达式格式将其编写为:T#[0-9]*m?[0-9]*s?[0-9]*ms?但是,总会有至少一位数字和至少一个单位。

这是我在函数内部使用的逻辑:function diagram

这是我应用于DataFrame中原始时间列的函数:

def convert_time(string):
    if string == 'T#0ms':
        return 0
    else:
        ms_ = False if string.find('ms') == -1 else True
        string = string[2:-2] if ms_ else string[2:]
        s_ = False if string.find('s') == -1 else True
        m_ = False if string.find('m') == -1 else True
        if m_ and s_ and ms_:
            m, temp = string.split('m')
            s, ms = temp.split('s')
            return int(m)*60 + int(s) + int(ms)*0.001
        elif not m_ and s_ and ms_:
            s, ms = string.split('s')
            return int(s) + 0.001 * int(ms)
        elif m_ and not s_ and ms_:
            m, ms = string.split('m')
            return 60*int(m) + 0.001 * int(ms)
        elif not m_ and not s_ and ms_:
            return int(string) * 0.001
        elif m_ and s_ and not ms_:
            m, s = string.split('m')
            return 60*int(m) + int(s[:-1])
        elif not m_ and s_ and not ms_:
            return int(string[:-1])
        elif m_ and not s_ and not ms_:
            return int(string[:-1]) * 60
        elif not m_ and not s_ and not ms_:
            return -1

像上面提到的那样,缺乏经验不允许我编写更好的函数来产生相似的输出(或者更好,例如直接以时间格式输出)。希望这会很有趣,以得到一些改进的提示。谢谢。

python python-3.x dataframe
2个回答
0
投票
def str_to_sec(time_str):
    return_int = 0
    cur_int = 0

    # remove start characters and replace 'ms' with a single character as unit
    time_str = time_str.replace('T#','').replace('ms', 'p')

    # build multiplier matrix
    split_order = ['m', 's', 'p']
    multiplier = [60, 1, 0.001]
    calc_multiplier_dic = dict(zip(split_order, multiplier))

    # loop through string and update the cumulative time
    for ch in time_str:
        if ch.isnumeric():
            cur_int = cur_int * 10 + int(ch)
            continue
        if ch.isalpha():
            return_int += cur_int * calc_multiplier_dic[ch]
            cur_int = 0

    return return_int

0
投票

使用正则表达式:

import re

def f(x):
    x = x[2:]
    time = re.findall(r'\d+', x)
    timeType = re.findall(r'[a-zA-Z]+',x)
    #print(time,timeType)
    total = 0
    for i,j in zip(time,timeType):
        if j == 'm':
            total += 60*float(i) 
        elif j =='s':
            total+=float(i) 
        elif j == 'ms':
            total += float(i)/1000
    return total 

test1 = 'T#3853m10s575ms'   # 231190.575 [seconds]
test2 = 'T#10s575ms'        # 10.575
test3 = 'T#3853m575ms'      # 231180.575
test4 = 'T#575ms'           # 0.575
test5 = 'T#3853m10s'        # 231190
test6 = 'T#10s'             # 10
test7 = 'T#3853m'           # 231180
test8 = 'T#0ms'             # 0

arr = [test1,test2,test3,test4,test5,test6,test7,test8]

for t in arr:
    print(f(t))

输出:

231190.575
10.575
231180.575
0.575
231190.0
10.0
231180.0
0.0
[Finished in 0.7s]

或者,如果您有更多的时间类型(例如小时,天等),则可以使外观代码更小。使用地图

import re
def symbol(j):
    if j == 'm':
        return 60 
    elif j =='s':
        return 1  
    elif j == 'ms':
        return .001

def f(x):
    x = x[2:]
    time = list(map(float,re.findall(r'\d+', x)))
    timeType = list(map(symbol,re.findall(r'[a-zA-Z]+',x)))
    #print(time,timeType)
    return sum([a*b for a,b in zip(timeType,time)]) 

test1 = 'T#3853m10s575ms'   # 231190.575 [seconds]
test2 = 'T#10s575ms'        # 10.575
test3 = 'T#3853m575ms'      # 231180.575
test4 = 'T#575ms'           # 0.575
test5 = 'T#3853m10s'        # 231190
test6 = 'T#10s'             # 10
test7 = 'T#3853m'           # 231180
test8 = 'T#0ms'             # 0

arr = [test1,test2,test3,test4,test5,test6,test7,test8]

for t in arr:
    print(f(t))
© www.soinside.com 2019 - 2024. All rights reserved.