1

I have a numpy array containing integers and slice objects, e.g.:

x = np.array([0,slice(None)])

How do I retrieve the (logical) indices of the integers or slice objects? I tried np.isfinite(x) (producing an error), np.isreal(x) (all True), np.isscalar(x) (not element-wise), all in vain. What seems to work though is

ind = x<np.Inf       # Out[1]: array([True, False], dtype=bool)

but I'm reluctant to use a numerical comparison on an object who's numerical value is completely arbitrary (and might change in the future?). Is there a better solution to achieve this?

2
  • 2
    All items in a numpy array share a same dtype. If you look at x.dtype you will see that it is dtype('object'). So from a vectorized type checking point of view, they are all the same. Do you really need to mix different things in the same array? It is probably easier to refactor your code a little to take advantage of numpy, than to make numpy work the way you are doing. Commented Dec 13, 2012 at 17:52
  • @Jaime Actually, the data is stored as a list: [0,slice(None)]; from this list I can retrieve the slice objects (or the indices of those) using a list comprehension, but I thought it would be quicker to (mis)use a numpy array for that purpose. Indeed, this is 4 times faster than a list comprehension, if it weren't for the fact that the conversion from list to array is 10 times slower ... :-( So, problem solved/evaded: better use a list comprehension. For multiple selections in the same list, though, the array method may still pay off. Anyway, thanks for your input! Commented Dec 14, 2012 at 14:27

1 Answer 1

1

You can do this:

import numpy as np
checker = np.vectorize( lambda x: isinstance(x,slice) )
x = np.array([0,slice(None),slice(None),0,0,slice(None)])
checker(x)
#array([False,  True,  True, False, False,  True], dtype=bool)
Sign up to request clarification or add additional context in comments.

Comments

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.