熊猫datetime64列的中位数

T-J*_*Jay 4 python python-datetime datetime64

有没有一种方法可以计算并以datetime格式返回datetime列的中位数?我想计算datetime64 [ns]格式的python列的中位数。以下是该列的示例:

df['date'].head()

0   2017-05-08 13:25:13.342
1   2017-05-08 16:37:45.545
2   2017-01-12 11:08:04.021
3   2016-12-01 09:06:29.912
4   2016-06-08 03:16:40.422
Run Code Online (Sandbox Code Playgroud)

名称:recency,dtype:datetime64 [ns]

我的目标是使中位数与上述日期列的日期时间格式相同:

尝试转换为np.array:

median_ = np.median(np.array(df['date']))
Run Code Online (Sandbox Code Playgroud)

但这引发了错误:

TypeError: ufunc add cannot use operands with types dtype('<M8[ns]') and dtype('<M8[ns]')
Run Code Online (Sandbox Code Playgroud)

转换为int64然后计算中位数并尝试将格式返回给datetime无效

df['date'].astype('int64').median().astype('datetime64[ns]')
Run Code Online (Sandbox Code Playgroud)

use*_*430 6

您还可以尝试通过一些转换来实现分位数(0.5),如果数据帧的长度是偶数,则与中位数并不完全相同,但这可能就足够了:

df['date'].astype('datetime64[ns]').quantile(.5)
Run Code Online (Sandbox Code Playgroud)


kab*_*nus 5

只取中间值怎么样?

dates = list(df.sort('date')['date'])
print dates[len(dates)//2]
Run Code Online (Sandbox Code Playgroud)

如果表格已排序,您甚至可以跳过一行。