[英]Remove the days in the timedelta object
I have a column in a pandas dataframe
that is created after subtracting two times.我在熊猫
dataframe
有一列是在减去两次后创建的。 I now have a timedelta
object like this -1 days +02:45:00
.我现在有一个像这样的
timedelta
对象-1 days +02:45:00
。 I just need to remove the -1 days and want it to be 02:45:00
.我只需要删除 -1 天并希望它是
02:45:00
。 Is there a way to do this?有没有办法做到这一点?
I think you can subtract days
converted to timedeltas:我认为您可以减去转换为 timedeltas 的
days
数:
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'>
Or convert timedeltas to strings and extract strings between days
and .
或者将 timedeltas 转换为字符串并在
days
和.
: :
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'>
I found this method easy, others didnt work for me我发现这个方法很简单,其他人对我不起作用
df['column'] = df['column'].astype(str).map(lambda x: x[7:])
It slices of the days part and you only get time part它分割了日子的一部分,而你只得到了时间的一部分
If your column is named time1, you can do it like this:如果您的列名为 time1,您可以这样做:
import pandas as pd
import datetime as dt
df['time1'] = pd.to_datetime(str(df.time1)[11:19]) #this slice can be adjusted
df['time1'] = df.time1.dt.time
this is going to convert the timedelta to str, slice the time part from it, convert it to datetime and extract the time from that.这会将 timedelta 转换为 str,从中切出时间部分,将其转换为 datetime 并从中提取时间。
I found a very easy solution for other people who may encounter this problem:我为可能遇到此问题的其他人找到了一个非常简单的解决方案:
if timedelta_obj.days < 0:
timedelta_obj.days = datetime.timedelta(
seconds=timedelta_obj.total_seconds() + 3600*24)
I think what you want to do is to minus two timestamps while ignoring the date.我认为您想要做的是在忽略日期的同时减去两个时间戳。 One simple way to do that is to set the two timestamps with the same date before minus.
一种简单的方法是在减去之前将两个时间戳设置为相同的日期。
import pandas as pd
start_time = pd.Timestamp(2007, 12, 5, 21, 24, 36)
end_time = pd.Timestamp(2007, 12, 6, 20, 24, 36)
start_time - end_time # which returns Timedelta('-1 days +01:00:00')
What you can do is just set end_time with the same date as start_time:您可以做的只是将 end_time 设置为与 start_time 相同的日期:
import pandas as pd
start_time = pd.Timestamp(2007, 12, 5, 21, 24, 36)
end_time = pd.Timestamp(2007, 12, 6, 20, 24, 36)
end_time = end_time.replace(year=start_time.year, month=start_time.month, day=start_time.day)
start_time - end_time # which returns Timedelta('0 days +01:00:00')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.