如何使用C API创建datetime64对象的Numpy数组? [英] How to create of Numpy array of datetime64 objects using C API?
问题描述
我需要从C/C ++代码创建一个numpy datetime64对象数组.如您所见,对于NPY_LONGLONG
和NPY_VOID
,我做到了.对于NPY_DATETIME
类型,我需要做同样的事情.
I need to create an array of numpy datetime64 objects from C/C++ code. As you can see for NPY_LONGLONG
and NPY_VOID
I did it. I need to do the same thing for NPY_DATETIME
type.
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
类型的内部表示形式的文档,所以我不知道它是否具有固定的大小,结构.
The problem is that there is no documentation about what is the internal representation of NPY_DATETIME
type, so I don't know if it has an fixed size, structure or not.
如果您像我对NPY_LONGLONG
和NPY_VOID
所做的示例一样,那将很棒.
It would be great if you put an example like I did for NPY_LONGLONG
and NPY_VOID
.
推荐答案
我找到了一个很好的解决方案.这是我的函数,它从C缓冲区创建numpy数组.
I found a good solution. Here is my function that creates numpy array from a C buffer.
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].
dtype
is M8[ms] or M8[us] or M8[ns].
这篇关于如何使用C API创建datetime64对象的Numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!