【问题标题】:Pandas; transform column with MM:SS,decimals into number of seconds熊猫;将带有 MM:SS、小数的列转换为秒数
【发布时间】:2013-12-26 16:01:54
【问题描述】:

嘿:花了几个小时试图做一件很简单的事情,但还是想不通。

我有一个数据框,其中包含一列 df['Time'] ,其中包含时间,从 0 开始,最多 20 分钟,如下所示:

1:10,10
1:16,32
3:03,04

第一个是分钟,第二个是秒,第三个是毫秒(只有两位数)。

有没有办法使用 Pandas 自动将该列转换为秒,并且不将该列作为系列的时间索引?

我已经尝试了以下方法,但它不起作用:

pd.to_datetime(df['Time']).convert('s')   # AttributeError: 'Series' object has no attribute 'convert'

如果唯一的方法是解析时间,只需指出这一点,我将为这个问题准备一个适当/详细的答案,不要浪费你的时间 =) 谢谢!

【问题讨论】:

    标签: python string parsing pandas timedelta


    【解决方案1】:

    代码:

    import pandas as pd
    import numpy as np
    import datetime
    df = pd.DataFrame({'Time':['1:10,10', '1:16,32', '3:03,04']})
    df['time'] = df.Time.apply(lambda x: datetime.datetime.strptime(x,'%M:%S,%f'))
    df['timedelta'] = df.time - datetime.datetime.strptime('00:00,0','%M:%S,%f')
    df['secs'] = df['timedelta'].apply(lambda x: x / np.timedelta64(1, 's'))
    print df
    

    输出:

          Time                       time       timedelta    secs
    0  1:10,10 1900-01-01 00:01:10.100000 00:01:10.100000   70.10
    1  1:16,32 1900-01-01 00:01:16.320000 00:01:16.320000   76.32
    2  3:03,04 1900-01-01 00:03:03.040000 00:03:03.040000  183.04
    

    如果您也有负时间增量:

    import pandas as pd
    import numpy as np
    import datetime
    
    import re
    regex = re.compile(r"(?P<minus>-)?((?P<minutes>\d+):)?(?P<seconds>\d+)(,(?P<centiseconds>\d{2}))?")
    
    def parse_time(time_str):
        parts = regex.match(time_str)
        if not parts:
            return
        parts = parts.groupdict()
        time_params = {}
        for (name, param) in parts.iteritems():
            if param and (name != 'minus'):
                time_params[name] = int(param)
        time_params['milliseconds'] = time_params['centiseconds']*10
        del time_params['centiseconds']
        return (-1 if parts['minus'] else 1) * datetime.timedelta(**time_params)
    
    df = pd.DataFrame({'Time':['-1:10,10', '1:16,32', '3:03,04']})
    df['timedelta'] = df.Time.apply(lambda x: parse_time(x))
    df['secs'] = df['timedelta'].apply(lambda x: x / np.timedelta64(1, 's'))
    print df
    

    输出:

           Time        timedelta    secs
    0  -1:10,10 -00:01:10.100000  -70.10
    1   1:16,32  00:01:16.320000   76.32
    2   3:03,04  00:03:03.040000  183.04
    

    【讨论】:

    • 谢谢!但是,您如何将每一行转换为秒?如:['70.10'、'76.32'等]
    • 非常感谢,您的回答解决了我的问题。但我想知道,如果时间涉及负时间怎么办? (即:我们正在跟踪一个事件,我们想在 20 秒前做某事)。解决方案也有效吗?
    猜你喜欢
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2021-09-07
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多