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

Odd behaviour when applying `Pandas.Timedelta.total_seconds`

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

作为解决方案,我尝试使用 total_seconds() 函数和 apply() 来获取列的数字表示,但是这种行为对我来说似乎很奇怪,因为 NaT 我的 Timedelta 列中的值变成了 -9.223372e+09 但当 total_seconds() 用于没有 apply()

的标量时,它们会导致 NaN

一个最小的例子:

test = pd.Series([np.datetime64('nat'),np.datetime64('nat')])
res = test.apply(pd.Timedelta.total_seconds)
print(res)

产生:

0   -9.223372e+09
1   -9.223372e+09
dtype: float64

鉴于:

res = test.iloc[0].total_seconds()
print(res)

产量:

nan

第二个示例的行为是理想的,因为我希望执行聚合等并传播 missing/invalid 值。这是一个错误吗?

您应该使用 .dt.total_seconds() 方法,而不是将 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

另一个演示:

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