Dirk Paul
Dirk Paul

Reputation: 137

Strange things about numpy indexing using empty ndarray

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!

Upvotes: 5

Views: 2121

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

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.

Upvotes: 4

piRSquared
piRSquared

Reputation: 294198

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

Try:

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

Upvotes: 3

Related Questions