2012-07-21 24 views
4

我是新来的numpy,我试图用它来做一些简单的统计,例如计算中位数或stddev(我知道我应该看看熊猫,但首先我想让自己熟悉numpy)。其中的“列”我想探讨的是一个时间差(即其类型timedelta64 numpy的类型),但我不能直接应用这些统计ufuncs:为什么timedeltas不能在numpy中相乘/分割?

----> 1 age_request.std() 

TypeError: ufunc 'divide' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule 'safe' 

为什么会这样?

回答

2

看看documentation for datetime。它列出了您可以在timedelta对象上执行的操作。划分是这样完成的:

t1 = t2 // i 

请注意,这会计算地板并丢弃任何剩余部分。

据我所知,你只能在timedelta对象上做这些操作。虽然也许我错了,你可以使用numpy操作。

我建议timedelta对象转换为微秒,然后做你的事业部,标准偏差,中位数等:

tdMicrosecs = td.microseconds + 1000.0 * td.seconds + 86400000000.0 * td.days 
tdQuotient = tdMicrosecs/i 

(我要补充,虽然,我不完全知道什么是最大整数值是python可以存储的,如果tdMicrosecs可以超过它。)

+3

或者在Python> = 2.7中,使用timedelta.to_seconds(),它给出了浮点数的秒数。 – mtrw 2012-07-21 15:42:52

+0

这可能会更好! :) – carmenism 2012-07-21 15:43:33

+2

在Python 3.3上使用timedelta.total_seconds()而不是 – 2014-02-12 11:19:21

相关问题