Home > Software design >  Unable to assign values to numpy array in cython
Unable to assign values to numpy array in cython

Time:12-18

I am fairly new to parallel programming in cython and I was trying to create a 1D array of size 3 from numpy, however I am unable to assign values to this array unless I specify it element by element.

    import numpy as np
    cimport numpy as cnp

    cdef int num = 3
    cdef cnp.ndarray[cnp.int_t, ndim = 1] Weight = np.ones((num), dtype = "int")
    Weight[2] = 6
    print(Weight)

Output -> [1 1 6]

    Weight = cnp.ndarray([1,2,3])

Output -> ValueError: Buffer has wrong number of dimensions (expected 1, got 3)

CodePudding user response:

In the comments I suggested changing:

Weight = cnp.ndarray([1,2,3])

to

Weight = np.array([1,2,3])

Just to clarify my comment a bit more:

The line

cdef cnp.ndarray[cnp.int_t, ndim = 1] Weight = np.ones((num), dtype = "int")

is effectively two parts:

  1. cdef cnp.ndarray[cnp.int_t, ndim = 1] Weight

    a declaration only. This allocated no memory, it merely creates a variable that can be a reference to a numpy array, and which allows quick indexing.

  2. Weight = np.ones((num), dtype = "int")

    This is a normal Python call to np.ones which allocates memory for the array. It is largely un-accelerated by Cython. From this point on Weight is a reference to that allocated array and can be used to change it. Note that Weight = ... in following lines will change what array Weight references.

I therefore suggest you skip the np.ones step and just do

cdef cnp.ndarray[cnp.int_t, ndim = 1] Weight = np.ones([1,2,3], dtype = "int")

Be aware that the only bit of Numpy that using these declarations accelerates is indexing into the array. Almost all other Numpy calls happen through the normal Python mechanism and will require the GIL and will happen at normal Python speed.

  • Related