numpy用datetime64数字化

时间:2014-12-07 18:31:57

标签: python numpy pandas datetime64

我似乎无法使用numpy.digitize来处理datetime64:

date_bins = np.array([np.datetime64(datetime.datetime(2014, n, 1), 's') for n in range(1,13)])
np.digitize(date_bins, date_bins)

它出现以下错误:

TypeError: Cannot cast array data from dtype('<M8[s]') to dtype('float64') according to the rule 'safe'

这是预期的行为吗?

1 个答案:

答案 0 :(得分:4)

获取i8值的datetime视图:

>>> date_bins_i8 = date_bins.view('i8')
>>> np.digitize(date_bins_i8, date_bins_i8)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

i8是64位整数数据类型,view构造数组内存的视图。