Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctypes - numpy array with no shape?

I am using a python wrapper to call functions of a c++ dll library. A ctype is returned by the dll library, which I convert to numpy array

score = np.ctypeslib.as_array(score,1) 

however, the array has no shape?

score
>>> array(-0.019486344729027664)

score.shape
>>> ()

score[0]
>>> IndexError: too many indices for array

How can I extract a double from the score array?

Thank you.

like image 287
Alejandro Simkievich Avatar asked Jan 21 '16 18:01

Alejandro Simkievich


1 Answers

You can access the data inside a 0-dimensional array via indexing [()].

For example, score[()] will retrieve the underlying data in your array.

The idiom is in fact consistent:

# x, y, z are 0-dim, 1-dim, 2-dim respectively
x = np.array(1)
y = np.array([1, 2, 3])
z = np.array([[1, 2, 3], [4, 5, 6]])

# use 0-dim, 1-dim, 2-dim tuple indexers respectively
res_x = x[()]      # 1
res_y = y[(1,)]    # 2
res_z = z[(1, 2)]  # 6

Tuples seem unnatural because you don't need to use them explicitly for the 1d and 2d cases, i.e. y[1] and z[1, 2] suffice. That option isn't available for the 0-dim case, so use the zero-length tuple.

like image 109
jpp Avatar answered Sep 19 '22 07:09

jpp