2017-05-10 32 views
1

有沒有辦法計算和返回日期時間格式的日期時間列的中位數? 我想計算python中datetime64 [ns]格式的列的中位數。下面是一個示例,以列:熊貓datetime64列的中位數

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 

名稱:新近度,D型細胞:datetime64 [NS]

我的目標是在同一日期時間格式的中位數作爲上述日期列:

試圖轉換爲np.array:

median_ = np.median(np.array(df['date'])) 

但拋出的錯誤:

TypeError: ufunc add cannot use operands with types dtype('<M8[ns]') and dtype('<M8[ns]') 

轉換爲Int64的,然後計算中位數和嘗試返回格式的日期時間不工作

df['date'].astype('int64').median().astype('datetime64[ns]') 

回答

2

如何只取中間值?

dates = list(df.sort('date')['date']) 
print dates[len(dates)//2] 

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

+0

謝謝@kabanus。這很好。我沒有想到要對列的長度進行排序和使用。 –

+0

@ T-Jay樂於助人。不要忘記接受讓我感覺良好並且爲了他人的利益。 – kabanus

0

你靠近時,median()返回float所以將其轉換爲一個int第一:

import math 

median = math.floor(df['date'].astype('int64').median()) 

然後轉換int表示日期爲datetime64

result = np.datetime64(median, "ns") #unit: nanosecond 
0

您也可以嘗試分位數(0.5)進行一些轉換,如果數據幀的長度是偶數,則與中位數不完全相同,但這可能就足夠了:

df['date'].astype('datetime64[ns]').quantile(.5)