删除timedelta对象中的日期 [英] Remove the days in the timedelta object

查看:48
本文介绍了删除timedelta对象中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫 dataframe 中有一列,该列是减去两次后创建的.我现在有一个 timedelta 对象,像这样的 -1天+02:45:00 .我只需要删除-1天,并希望它为 02:45:00 .有办法吗?

I have a column in a pandas dataframe that is created after subtracting two times. I now have a timedelta object like this -1 days +02:45:00. I just need to remove the -1 days and want it to be 02:45:00. Is there a way to do this?

推荐答案

我认为您可以减去

I think you can subtract days converted to timedeltas:

td = pd.to_timedelta(['-1 days +02:45:00','1 days +02:45:00','0 days +02:45:00'])
df = pd.DataFrame({'td': td})

df['td'] = df['td'] - pd.to_timedelta(df['td'].dt.days, unit='d')

print (df.head())

        td
0 02:45:00
1 02:45:00
2 02:45:00

print (type(df.loc[0, 'td']))
<class 'pandas._libs.tslibs.timedeltas.Timedelta'>

或将timedelta转换为字符串,并在 days 之间提取字符串.:

Or convert timedeltas to strings and extract strings between days and .:

df['td'] = df['td'].astype(str).str.extract('days (.*?)\.')
print (df.head())
          td
0  +02:45:00
1   02:45:00
2   02:45:00

print (type(df.loc[0, 'td']))
<class 'str'>

这篇关于删除timedelta对象中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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