14

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.

5
  • 1
    That is a shape; it's shape (), aka 0-dimensional. Commented Jan 21, 2016 at 18:15
  • thanks a lot. is there any way to extract the double inside the array? I guess that is the question in the end Commented Jan 21, 2016 at 18:16
  • You can use float(score). But how are you ending up with a 0-d array, i.e. what's the initial type and value of score? Commented Jan 21, 2016 at 18:18
  • Why are you calling np.ctypeslib.as_array on this thing? 1 isn't a valid shape, and if there's only one value, why do you want to use np.ctypeslib.as_array to retrieve it? Why not go through the normal ctypes interface? Commented Jan 21, 2016 at 18:19
  • The shape parameter is only used for a pointer, so we know score isn't initially a pointer, else passing shape=1 would be an error. If you pass as_array a scalar such as c_double(-0.19), it stores an __array_interface__ property on the c_double type with shape=(). However, in NumPy 1.8.2 this actually creates an array with shape=(1,). Maybe in older versions it creates a scalar 'array'. Commented Jan 21, 2016 at 18:42

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

3 Comments

what is this sorcery ?
() is a tuple with the length of 0. It's exactly the same operation as the good old array[(3, 4)].
Alternatively, for arrays with a single value, array.item() will return a scalar regardless of how dimensions it has. np.array(0).item() == np.atleast_3d(0).item().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.