numpy - 在 cython 中使用日期时间和 bool

标签 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

谢谢

最佳答案

您无法在 C 级别直接与这些类型交互,但您可以从 View 中使用它们。例如:

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]')

关于numpy - 在 cython 中使用日期时间和 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33522626/

相关文章:

python - 帮忙看看如何pickle ufunc?

python - 如何在python中将二维numpy方形数组旋转45度?

python - 有效地初始化 Cython Memoryview

c++ - "using Time = cppClassDefinition<withT>"的 Cython 等价物

python - 包 "not found as"错误中的 Cython pickle

python - Cython:如何重新编译 cython .pyx

python - 在 python 中计算 numpy 的欧氏距离

python - 最有效的方法(lo <= k && k <= hi)? 1 : 0 for k a numpy array, lo, hi 常量

python - 散点图的矩阵元素

python - 如何清理由cython扩展编译的文件