Thành Đạt
Thành Đạt

Reputation: 327

Slicing array with numpy?

import numpy as np
r = np.arange(36)
r.resize((6, 6))

print(r)
# prints:
# [[ 0  1  2  3  4  5]
#  [ 6  7  8  9 10 11]
#  [12 13 14 15 16 17]
#  [18 19 20 21 22 23]
#  [24 25 26 27 28 29]
#  [30 31 32 33 34 35]]

print(r[:,::7])
# prints:
# [[ 0]
#  [ 6]
#  [12]
#  [18]
#  [24]
#  [30]]

print(r[:,0])
# prints:
# [ 0  6 12 18 24 30]

The r[:,::7] gives me a column, the r[:,0] gives me a row, they both have the same numbers. Would be glad if someone could explain to me why?

Upvotes: 0

Views: 56

Answers (1)

MSeifert
MSeifert

Reputation: 152850

Because the step argument is greater than the corresponding shape so you'll just get the first "row". However these are not identical (even if they contain the same numbers) because the scalar index in [:, 0] flattens the corresponding dimension (so you'll get a 1D array). But [:, ::7] will keep the number of dimensions intact but alters the shape of the step-sliced dimension.

Upvotes: 2

Related Questions