Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent advanced indexing in NumPy

Tags:

python

numpy

Why are the following indexing forms produce differently shaped outputs?

a = np.zeros((5, 5, 5, 5))
print(a[:, :, [1, 2], [3, 4]].shape)
# (5, 5, 2)

print(a[:, :, 1:3, [3, 4]].shape)
#(5, 5, 2, 2)

Almost certain I'm missing something obvious.

like image 424
Vadim Kantorov Avatar asked Jul 19 '17 17:07

Vadim Kantorov


1 Answers

[1, 2], [3, 4] doesn't mean "select indices 1 and 2 in one dimension and 3 and 4 in another". It means "select the pairs of indices (1, 3) and (2, 4)".

Your first expression select all elements at locations of the form a, b, c, d where a and b can be any index and c and d must be either the pair (1, 3) or the pair (2, 4).

Your second expression selects all elements at locations of the form a, b, c, d where a and b can be any index, c must be in the half-open range [1, 3), and d must be either 3 or 4. Unlike the first one, c and d are allowed to be (2, 3) or (1, 4).


Note that using both basic and advanced indexing in the same indexing expression (which mostly means mixing : and advanced indexing) has unintuitive effects on the order of the axes of the result. It's best to avoid mixing them.

like image 142
user2357112 supports Monica Avatar answered Sep 28 '22 17:09

user2357112 supports Monica