User guide
NumPy User Guide, Release 1.9.0
and types
>>> x = np.array([[ 1.+0.j, 2.+0.j], [ 0.+0.j, 0.+0.j], [ 1.+1.j, 3.+0.j]])
2.2.3 Intrinsic Numpy Array Creation
Numpy has built-in functions for creating arrays from scratch:
zeros(shape) will create an array filled with 0 values with the specified shape. The default dtype is float64.
>>> np.zeros((2, 3)) array([[ 0., 0., 0.], [ 0., 0., 0.]])
ones(shape) will create an array filled with 1 values. It is identical to zeros in all other respects.
arange() will create arrays with regularly incrementing values. Check the docstring for complete information on the
various ways it can be used. A few examples will be given here:
>>> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.arange(2, 10, dtype=np.float)
array([ 2., 3., 4., 5., 6., 7., 8., 9.])
>>> np.arange(2, 3, 0.1)
array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
Note that there are some subtleties regarding the last usage that the user should be aware of that are described in the
arange docstring.
linspace() will create arrays with a specified number of elements, and spaced equally between the specified beginning
and end values. For example:
>>> np.linspace(1., 4., 6)
array([ 1. , 1.6, 2.2, 2.8, 3.4, 4. ])
The advantage of this creation function is that one can guarantee the number of elements and the starting and end
point, which arange() generally will not do for arbitrary start, stop, and step values.
indices() will create a set of arrays (stacked as a one-higher dimensioned array), one per dimension with each repre-
senting variation in that dimension. An example illustrates much better than a verbal description:
>>> np.indices((3,3))
array([[[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]])
This is particularly useful for evaluating functions of multiple dimensions on a regular grid.
2.2.4 Reading Arrays From Disk
This is presumably the most common case of large array creation. The details, of course, depend greatly on the format
of data on disk and so this section can only give general pointers on how to handle various formats.
Standard Binary Formats
Various fields have standard formats for array data. The following lists the ones with known python libraries to read
them and return numpy arrays (there may be others for which it is possible to read and convert to numpy arrays so
check the last section as well)
HDF5: PyTables
FITS: PyFITS
12 Chapter 2. Numpy basics