应用`Pandas.Timedelta.total_seconds`时的奇怪行为

sea*_*ull 4 python datetime timedelta pandas

我有一个带有Timedelta类型列的pandas数据框。我使用groupby和一个单独的month列来按月创建这些分组Timdelta,然后尝试在触发该列的列上使用该agg函数min, max, meanTimedeltaDataError: No numeric types to aggregate

作为一种解决方案,我尝试使用total_seconds()函数以及apply()获取列的数字表示形式,但是对于我来说,行为似乎很奇怪,因为NaT我将Timedelta列中的值转换为,-9.223372e+09但是它们导致在标量上使用NaNtotal_seconds()不使用apply()

一个最小的例子:

test = pd.Series([np.datetime64('nat'),np.datetime64('nat')])
res = test.apply(pd.Timedelta.total_seconds)
print(res)
Run Code Online (Sandbox Code Playgroud)

产生:

0   -9.223372e+09
1   -9.223372e+09
dtype: float64
Run Code Online (Sandbox Code Playgroud)

而:

res = test.iloc[0].total_seconds()
print(res)
Run Code Online (Sandbox Code Playgroud)

产量:

nan
Run Code Online (Sandbox Code Playgroud)

由于我希望执行聚合等并传播缺失/无效值,因此需要第二个示例的行为。这是一个错误吗?

Max*_*axU 6

您应该使用.dt.total_seconds()method,而不是将pd.Timedelta.total_seconds函数应用于datetime64[ns]dtype列:

In [232]: test
Out[232]:
0   NaT
1   NaT
dtype: datetime64[ns]  # <----

In [233]: pd.to_timedelta(test)
Out[233]:
0   NaT
1   NaT
dtype: timedelta64[ns]  # <----

In [234]: pd.to_timedelta(test).dt.total_seconds()
Out[234]:
0   NaN
1   NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)

另一个演示:

In [228]: s = pd.Series(pd.to_timedelta(['03:33:33','1 day','aaa'], errors='coerce'))

In [229]: s
Out[229]:
0   0 days 03:33:33
1   1 days 00:00:00
2               NaT
dtype: timedelta64[ns]

In [230]: s.dt.total_seconds()
Out[230]:
0    12813.0
1    86400.0
2        NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)