我有一个 pandas 数据框,其中有一列是 Timedelta
类型。我使用带有单独月份列的 groupby 按月创建这些 Timdelta
的组,然后我尝试将 agg
函数与 min, max, mean< 一起使用
在 Timedelta
列触发 DataError: No numeric types to aggregate
作为对此的解决方案,我尝试使用 total_seconds()
函数和 apply()
来获取列的数字表示,但是行为似乎很奇怪对我来说,因为我的 Timedelta
列中的 NaT
值变成了 -9.223372e+09
但它们导致了 NaN
当 total_seconds()
用于没有 apply()
一个最小的例子:
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
第二个示例的行为是理想的,因为我希望执行聚合等并传播缺失值/无效值。这是错误吗?
最佳答案
您应该使用.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
关于python - 应用 `Pandas.Timedelta.total_seconds` 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48168209/