如何使用C API创建datetime64对象的Numpy数组?

2024-09-28 22:08:55 发布

您现在位置:Python中文网/ 问答频道 /正文

<>我需要从C/C++代码中创建一个NUMPY DATETEM64对象数组。正如你看到的NPY_LONGLONGNPY_VOID我做到了。我需要对NPY_DATETIME类型执行相同的操作。在

PyObject *arr1 = PyArray_SimpleNew(1, &dims, NPY_LONGLONG);
PyObject *arr2 = PyArray_New(&PyArray_Type, 1, &dims, NPY_VOID, NULL, NULL, item_size, 0, NULL);

问题是没有关于NPY_DATETIME类型的内部表示的文档,因此我不知道它是否具有固定的大小、结构。在

如果您像我为NPY_LONGLONGNPY_VOID举一个例子,那就太好了。在


Tags: 对象代码numpy类型datetime数组nullpyobject
1条回答
网友
1楼 · 发布于 2024-09-28 22:08:55

我找到了一个好办法。这是我的函数,它从一个C缓冲区创建numpy数组。在

PyObject* create_datetime_array(int index, std::string const &dtype)
{
    int buffer_size = this->elements_count*sizeof(omd::OT_int64);
    npy_intp dims = this->elements_count;
    PyObject *date_type = Py_BuildValue("s", dtype.c_str());
    PyArray_Descr *descr;
    PyArray_DescrConverter(date_type, &descr);
    Py_XDECREF(date_type);
    PyObject *arr = PyArray_SimpleNewFromDescr(1, &dims, descr);
    memcpy(PyArray_BYTES((PyArrayObject *)arr), &(this->int64_data[index][0]), buffer_size);
    return arr;
}

dtype是M8[ms]或M8[us]或M8[ns]。在

相关问题 更多 >