Use the np.array() constructor to create an
array with any number of dimensions.
np.array(object, dtype=None)
object
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.
The 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.
dtype
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
type.
To create a vector of values, use np.array(, where S) is a sequence (list or tuple).
Unlike Python lists, when you print an array, it doesn't
show commas between the elements.
S
>>> 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[0] 2.4 >>> print d1[2] 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
dtype= keyword
argument to Dnp.array(), where is one of the Ddtype type objects described in Section 3, “Basic types”. In the example below, the first array
will have int (integer) type, and the second
one will have type float.
>>> 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 [6] as
the argument; this gives us a one-dimensional array with six
zeros in it.
>>> z = np.zeros([6]) >>> print z [ 0. 0. 0. 0. 0. 0.] >>> z[3] = 46.4 >>> z[5] = 82.2 >>> print z [ 0. 0. 0. 46.4 0. 82.2]