np.array() constructor to create an
array with any number of dimensions.
Values to be used in creating the array. This can be a sequence (to create a 1-d array), a sequence of sequences (for a 2-d array), a sequence of sequences of sequences, and so on. Each sequence may be either a list or a tuple.
object argument may also be an
existing array. The new array will be a copy, and
you can use the
dtype argument to
force the copy to be a different type.
To force the new array to be a given type, use one of the
type words as the second argument. For example,
array([1,2,3], dtype=np.float_) will give you an
array with those three values converted to floating-point
To create a vector of values, use
is a sequence (list or tuple).
Unlike Python lists, when you print an array, it doesn't
show commas between the elements.
>>> import numpy as np >>> d1=np.array([2.4, -1.5, 3.0, 8.8]) >>> print d1 [ 2.4 -1.5 3. 8.8]
To retrieve one value from a vector, use normal Python indexing: position 0 is the first element, position 2 is the third element, and so on.
>>> print d1 2.4 >>> print d1 3.0
You can use normal Python slicing on arrays as well.
>>> print d1[1:3] [-1.5 3. ]
If you want to force the array to use a specific type, use the
is one of the
dtype type objects described in Section 4, “Basic types”. In the example below, the first array
int (integer) type, and the second
one will have type
>>> print np.array([0, 1, 2, 3]) [0 1 2 3] >>> print np.array([0, 1, 2, 3], dtype=np.float_) [ 0. 1. 2. 3.]
If you don't have all the values together at once that you
need to build an array, you can instead create an array of
zeroes and fill the values in later. The argument to the
np.zeros() function is a sequence containing
the dimensions. In this example, we use
the argument; this gives us a one-dimensional array with six
zeros in it.
>>> z = np.zeros() >>> print z [ 0. 0. 0. 0. 0. 0.] >>> z = 46.4 >>> z = 82.2 >>> print z [ 0. 0. 0. 46.4 0. 82.2]