【问题标题】:How to convert irregular datetime to total seconds in python pandas如何在 python pandas 中将不规则日期时间转换为总秒数
【发布时间】:2018-09-27 07:44:58
【问题描述】:

我有一列持续时间,但值不同。有些持续时间只是时间格式,有些则与日期混合。我想要总秒数的持续时间列。我尝试使用 to_datetime 和 parse_date 方法转换列,但它无法工作。如何在熊猫中做到这一点?这是专栏:

enter image description here

【问题讨论】:

标签: python pandas datetime dataframe timedelta


【解决方案1】:

一种方法是将pd.Series.applytry / except 子句一起使用,它会按顺序尝试每种方法。

这种方法的好处是它可以接受timedeltadatetime 的各种潜在输入。

import pandas as pd, numpy as np

df = pd.DataFrame({'Mixed': ['03:59:49', '1904-01-01 04:06:08']})

def return_seconds(x):
    try:
        return pd.to_timedelta(x).total_seconds()
    except:
        try:
            dt = pd.to_datetime(x)
            return (dt - dt.normalize()).total_seconds()
        except:
            return np.nan

df['TotalSeconds'] = df['Mixed'].apply(return_seconds).astype(int)

print(df)

#                  Mixed  TotalSeconds
# 0             03:59:49         14389
# 1  1904-01-01 04:06:08         14768

【讨论】:

    【解决方案2】:

    过滤最后8个值,转换to_timedelta然后使用total_seconds

    df = pd.DataFrame({'col':['03:59:49', '1904-01-01 04:06:08']})
    
    df['new'] = pd.to_timedelta(df['col'].str[-8:]).dt.total_seconds().astype(int)
    print (df)
                       col    new
    0             03:59:49  14389
    1  1904-01-01 04:06:08  14768
    

    编辑:

    df['new'] = pd.to_timedelta(pd.to_datetime(df['col']).dt.strftime('%H:%M:%S')).dt.total_seconds().astype(int)
    

    【讨论】:

    • 当我将原始 Pandas 系列从 DataFrame 'data' 作为 data['duration'] = pd.to_timedelta(data['Finish_Netto'].str[-8:]).dt 传递时。 total_seconds().astype(int) 然后将错误显示为“ValueError: expected hh:mm:ss format”
    • @MAK - 似乎有一些其他格式的数据,所以请检查编辑的答案。
    • 数据是DataFrame,列类型是对象。现在它给出了另一个错误:“ TypeError: is not convertible to datetime”
    【解决方案3】:

    使用正则表达式:

    import pandas as pd
    df = pd.DataFrame({"a": ["03:59:49", "04:59:49", "1904-01-01 05:59:49", "1904-01-01 06:59:49"]})
    df["TotalSeconds"]  = pd.to_timedelta(df["a"].str.extract('(\d{2}:\d{2}:\d{2})')).dt.total_seconds()
    print(df)
    

    输出:

                         a  TotalSeconds
    0             03:59:49       14389.0
    1             04:59:49       17989.0
    2  1904-01-01 05:59:49       21589.0
    3  1904-01-01 06:59:49       25189.0
    

    【讨论】:

    • 感谢 Rakesh,它有效。但是有一些NaN值,如何删除或者转换为0。
    • 你可以使用df.fillna(0)
    • 例如:pd.to_timedelta(df["a"].str.extract('(\d{2}:\d{2}:\d{2})')).dt.total_seconds().fillna(0)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2012-09-17
    • 2015-01-30
    相关资源
    最近更新 更多