在cython

时间:2015-11-04 13:00:01

标签: numpy cython

如何在Cython中定义datetime64[D]timedelta[D]bool_ dtypes?

假设我有

cimport cython
cimport numpy as np
import numpy as np
from numpy cimport ndarray as ar

cpdef myfunc(...):
   cdef:
      ar[double] my_float_var
      ar[np.int64] my_int_var   
      ar[??] my_datetime64_var
      ar[??] my_bool_var

由于

1 个答案:

答案 0 :(得分:4)

您无法直接在c级与这些类型进行交互,但您可以从视图中使用它们。例如:

In [59]: import pandas as pd

In [60]: a = pd.date_range('2014-1-1', periods=10).values

In [61]: b = np.array([True, True, False, False, False, True, True, False, False, False])

In [62]: c = np.array([pd.Timedelta(days=1).asm8 for _ in range(10)])

In [63]: %%cython
    ...: cimport numpy as np
    ...: def func(np.ndarray[np.int64_t] dates,
    ...:          np.ndarray[np.uint8_t] bools,
    ...:          np.ndarray[np.int64_t] deltas):
    ...:     cdef:
    ...:         int i, N = len(dates)
    ...:     for i in range(N):
    ...:         if bools[i]:
    ...:             dates[i] += deltas[i]
    ...:     return dates.view('M8[ns]')

In [65]: func(a.view('int64'), b.view('uint8'), c.view('int64'))
Out[65]: 
array(['2014-01-01T18:00:00.000000000-0600',
       '2014-01-02T18:00:00.000000000-0600',
       '2014-01-02T18:00:00.000000000-0600',
       '2014-01-03T18:00:00.000000000-0600',
       '2014-01-04T18:00:00.000000000-0600',
       '2014-01-06T18:00:00.000000000-0600',
       '2014-01-07T18:00:00.000000000-0600',
       '2014-01-07T18:00:00.000000000-0600',
       '2014-01-08T18:00:00.000000000-0600',
       '2014-01-09T18:00:00.000000000-0600'], dtype='datetime64[ns]')