How to create of Numpy array of datetime64 objects using C API?

£可爱£侵袭症+ 提交于 2020-01-05 06:46:29

问题


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);

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.

It would be great if you put an example like I did for NPY_LONGLONG and NPY_VOID.


回答1:


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 is M8[ms] or M8[us] or M8[ns].



来源:https://stackoverflow.com/questions/25033711/how-to-create-of-numpy-array-of-datetime64-objects-using-c-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!