在数据帧中:如何使用python从timedelta中组合拉分和秒(mm:ss) [英] In dataframe: how to pull minutes and seconds combinedly(mm:ss) from timedelta using python

查看:32
本文介绍了在数据帧中:如何使用python从timedelta中组合拉分和秒(mm:ss)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过这些,但是通过这个我们只能得到小时/分钟/秒,但不能同时得到分钟和秒

i have already tried these but by this we can only get hour/minute/second but not both minute and second

在[7]:df['B'] = df['A'].dt.components['小时']

In[7]: df['B'] = df['A'].dt.components['hours']

df

出[7]:

     A  B

0 02:00:00 2

0 02:00:00 2

1 01:00:00 1

1 01:00:00 1

从此时间增量格式

0 0 天 00:02:02.246000

0 0 days 00:02:02.246000

1 0 天 00:01:59.127000

1 0 days 00:01:59.127000

我只需要几分钟和几秒钟,如何获得如下

i need only minutes and seconds, how to get it as below

02:02

01:59

推荐答案

您可以将 timedelta 转换为总秒数,并使用 divmod 函数从总秒数中提取分钟和秒数.

You can convert the timedelta to total seconds and use divmod function to extract minutes and seconds from the total seconds.

从第一个操作中删除了 lambda 函数.

Removed lambda function from the first operation.

    df['sec'] = df['A'].dt.total_seconds().astype(int)
    df['B'] = df.apply(lambda row: str(divmod(divmod(row['sec'], 3600)[1], 60)[0]).zfill(2)+':'+str(divmod(divmod(row['sec'], 3600)[1], 60)[1]).zfill(2), axis=1)

这篇关于在数据帧中:如何使用python从timedelta中组合拉分和秒(mm:ss)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆