Databases Reference
In-Depth Information
>>>
a
=
np
.
arange
(
10
)
>>>
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>
a
[::
-
1
]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
But if you try it on a dataset, you get the following:
>>>
dset
[::
-
1
]
ValueError: Step must be >= 1 (got -1)
Multidimensional and Scalar Slicing
By now you've gotten used to seeing the expression “
...
,” which is used as a slice in
examples. This object has the built-in name
Ellipsis
in the Python world. You can use
it as a “stand-in” for axes you don't want to bother specifying:
>>>
dset
=
f
.
create_dataset
(
'4d'
,
shape
=
(
100
,
80
,
50
,
20
))
>>>
dset
[
0
,
...
,
0
]
.
shape
(80, 50)
And of course you can get the entire contents by using
Ellipsis
by itself:
>>>
dset
[
...
]
.
shape
(100, 80, 50, 20)
There is one oddity we should discuss, which is that of
scalar
datasets. In NumPy, there
are two flavors of array containing one element. The first has shape (1,), and is an
ordinary one-dimensional array. You can get at the value inside by slicing or simple
indexing:
>>>
dset
=
f
.
create_dataset
(
'1d'
,
shape
=
(
1
,),
data
=
42
)
>>>
dset
.
shape
(1,)
>>>
dset
[
0
]
42
>>>
dset
[
...
]
array([42])
Note, by the way, how using
Ellipsis
provides an array with one element, whereas
integer indexing provides the element itself.
The second flavor has shape
()
(an empty tuple) and can't be accessed by indexing:
>>>
dset
=
f
.
create_dataset
(
'0d'
,
data
=
42
)
>>>
dset
.
shape
()
>>>
dset
[
0
]
ValueError: Illegal slicing argument for scalar dataspace
>>>
dset
[
...
]
array(42)
Note how using
Ellipsis
has again returned an array, in this case a scalar array.