考虑以下系列:
> df['time_delta']
0 -1 days +00:08:11
1 0 days 01:57:46
2 0 days 00:58:34
3 0 days 17:30:23
4 -1 days +21:44:34
5 -2 days +22:01:56
6 0 days 03:18:57
7 -1 days +21:44:48
8 -1 days +00:07:56
Name: time_delta, dtype: timedelta64[ns]
我想将此timedelta转换为总计 已签名秒。那就是:
例如:
0 days 00:01:05
=> 65
秒-1 days +23:58:30
=> -90
秒如何进行转换?
当我尝试平常时:
temp_df['seconds'] = temp_df['time_delta'].dt.seconds
我最终得到了:
time_delta seconds
0 -1 days +00:08:11 491
1 0 days 01:57:46 7066
2 0 days 00:58:34 3514
3 0 days 17:30:23 63023
4 -1 days +21:44:34 78274
5 -2 days +22:01:56 79316
6 0 days 03:18:57 11937
7 -1 days +21:44:48 78288
8 -1 days +00:07:56 476
正确处理正增量,但不负面增量。要看到这一点,请注意负增量似乎忽略了日偏移的符号。也就是说,在上面的例子中:
-1 days +21:44:48
应转换为-8112
秒,而不是78288
秒(错误的符号和值)。答案 0 :(得分:2)
只需在dt.total_seconds
之前调用abs
即可获得绝对值:
df['seconds'] = df['time_delta'].abs().dt.total_seconds()
示例:
In [63]:
df = pd.DataFrame({'date_time':pd.date_range(dt.datetime(2015,1,1,12,10,32), dt.datetime(2015,1,3,12,12,30,2))})
df['time_delta'] = df['date_time'] - dt.datetime(2015,1,2)
df
Out[63]:
date_time time_delta
0 2015-01-01 12:10:32 -1 days +12:10:32
1 2015-01-02 12:10:32 0 days 12:10:32
2 2015-01-03 12:10:32 1 days 12:10:32
In [64]:
df['time_delta'].abs().dt.total_seconds()
Out[64]:
0 42568
1 43832
2 130232
Name: time_delta, dtype: float64
要添加回来的标志,您可以与pd.Timedelta(0)
进行比较:
In [78]:
df['seconds'] = df['time_delta'].abs().dt.total_seconds()
df.loc[df['time_delta'] < pd.Timedelta(0), 'seconds'] = -df['seconds']
df
Out[78]:
date_time time_delta seconds
0 2015-01-01 12:10:32 -1 days +12:10:32 -42568
1 2015-01-02 12:10:32 0 days 12:10:32 43832
2 2015-01-03 12:10:32 1 days 12:10:32 130232
但是,我认为@Ami Tamory的答案是优越的
修改强>
在睡觉之后,我意识到这只是dt.total_seconds
:
In [137]:
df['time_delta'].dt.total_seconds()
Out[137]:
0 -42568
1 43832
2 130232
Name: time_delta, dtype: float64
答案 1 :(得分:2)
如果它是Timedelta
对象,只需将其除以Timedelta(seconds=1)
:
>>> pd.Timedelta(days=-1) / pd.Timedelta(seconds=1)
-86400.0