5

When I do numpy indexing, sometimes the index can be an empty list, in that way I want numpy to also return a empty array. For example:

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

b = []

print a[b]

This works perfectly fine! when the result gives me:

result:[]

But when I use ndarray as indexer, strange things happened:

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

b = []

c = np.array(b)

print a[c]

This gives me an error:

IndexError: arrays used as indices must be of integer (or boolean) type

However, When I do this:

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

b = []

d = np.arange(0, a.size)[b]

print a[d]

Then it works perfectly again:

result:[]

But when I check the type of c and d, they returns the same! Even the shape and everything:

print type(c), c.shape

print type(d), d.shape

result:<type 'numpy.ndarray'> (0L,)

result:<type 'numpy.ndarray'> (0L,)

So I was wondering if there is anything wrong with it? How come a[c] doesn't work but a[d] works? Can you explain it for me? Thank you!

2 Answers 2

4

There is a simple resolution numpy arrays have in a sense two types. their own type which is numpy.ndarray and the type of their elements which is specified by a numpy.dtype. Arrays used for indexing must have elements of integer or boolean dtype. In your examples you use two array creation methods with different default dtypes. The array factory which defaults to a float dtype if nothing else can be inferred from the template. And arange which uses an integer dtype unless you pass some float parameters. Since the dtype is also a property of the array it is specified and checked even if there are no elements. Empty lists are not checked for dtype because they do not have a dtype attribute.

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

Comments

3

numpy doesn't know what type the empty array is.

Try:

c = np.array(b, dtype=int)

2 Comments

Thanks this works! But I still think this is a little inconvenient. How come I have to tell numpy the type of an empty array. If this is a list I wouldn't have to worry about it.
It may be inconvenient for you in this context, but not necessarily for others. Most people don't need to make empty arrays as you did. The more common way of making a blank/empty array is np.zeros(n). That too is dtype float.

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.