Axes are defined for arrays with more than one dimension. A2-dimensional array has two corresponding axes: the first runningvertically downwards across rows (axis 0), and the second runninghorizontally across columns (axis 1).
Many operations can take place along one of these axes. For example,we can sum each row of an array, in which case we operate alongcolumns, or axis 1:
>>>x=np.arange(12).reshape((3,4))>>>xarray([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])>>>x.sum(axis=1)array([ 6, 22, 38])
A homogeneous container of numerical elements. Each element in thearray occupies a fixed amount of memory (hence homogeneous), andcan be a numerical element of a single type (such as float, intor complex) or a combination (such as(float,int,float)). Eacharray has an associated data-type (ordtype), which describesthe numerical type of its elements:
>>>x=np.array([1,2,3],float)>>>xarray([ 1., 2., 3.])>>>x.dtype# floating point number, 64 bits of memory per elementdtype('float64')# More complicated data type: each array element is a combination of# and integer and a floating point number>>>np.array([(1,2.0),(3,4.0)],dtype=[('x',int),('y',float)])array([(1, 2.0), (3, 4.0)], dtype=[('x', '<i4'), ('y', '<f8')])
Fast element-wise operations, called aufunc, operate on arrays.
A property of an object that can be accessed usingobj.attribute,e.g.,shape is an attribute of an array:
>>>x=np.array([1,2,3])>>>x.shape(3,)
NumPy can do operations on arrays whose shapes are mismatched:
>>>x=np.array([1,2])>>>y=np.array([[3],[4]])>>>xarray([1, 2])>>>yarray([[3], [4]])>>>x+yarray([[4, 5], [5, 6]])
Seenumpy.doc.broadcasting for more information.
A way to represent items in a N-dimensional array in the 1-dimensionalcomputer memory. In column-major order, the leftmost index “varies thefastest”: for example the array:
[[1,2,3],[4,5,6]]
is represented in the column-major order as:
[1,4,2,5,3,6]
Column-major order is also known as the Fortran order, as the Fortranprogramming language uses it.
An operator that transforms a function. For example, alogdecorator may be defined to print debugging information uponfunction execution:
>>>deflog(f):...defnew_logging_func(*args,**kwargs):...print("Logging call with parameters:",args,kwargs)...returnf(*args,**kwargs)......returnnew_logging_func
Now, when we define a function, we can “decorate” it usinglog:
>>>@log...defadd(a,b):...returna+b
Callingadd then yields:
>>>add(1,2)Logging call with parameters: (1, 2) {}3
Resembling a language dictionary, which provides a mapping betweenwords and descriptions thereof, a Python dictionary is a mappingbetween two objects:
>>>x={1:'one','two':[1,2]}
Here,x is a dictionary mapping keys to values, in this casethe integer 1 to the string “one”, and the string “two” tothe list[1,2]. The values may be accessed using theircorresponding keys:
>>>x[1]'one'>>>x['two'][1, 2]
Note that dictionaries are not stored in any specific order. Also,most mutable (seeimmutable below) objects, such as lists, may notbe used as keys.
For more information on dictionaries, read thePython tutorial.
numpy.ndarray.flattenfor details.A class definition gives the blueprint for constructing an object:
>>>classHouse(object):...wall_colour='white'
Yet, we have tobuild a house before it exists:
>>>h=House()# build a house
Now,h is called aHouse instance. An instance is thereforea specific realisation of a class.
A sequence that allows “walking” (iterating) over items, typicallyusing a loop such as:
>>>x=[1,2,3]>>>[item**2foriteminx][1, 4, 9]
enumerate::>>>keys=['a','b','c']>>>forn,kinenumerate(keys):...print("Key%d:%s"%(n,k))...Key 0: aKey 1: bKey 2: c
A Python container that can hold any number of objects or items.The items do not have to be of the same type, and can even belists themselves:
>>>x=[2,2.0,"two",[2,2.0]]
The listx contains 4 items, each which can be accessed individually:
>>>x[2]# the string 'two''two'>>>x[3]# a list, containing an integer 2 and a float 2.0[2, 2.0]
It is also possible to select more than one item at a time,usingslicing:
>>>x[0:2]# or, equivalently, x[:2][2, 2.0]
In code, arrays are often conveniently expressed as nested lists:
>>>np.array([[1,2],[3,4]])array([[1, 2], [3, 4]])
For more information, read the section on lists in thePythontutorial. For a mappingtype (key-value), seedictionary.
A boolean array, used to select only certain elements for an operation:
>>>x=np.arange(5)>>>xarray([0, 1, 2, 3, 4])>>>mask=(x>2)>>>maskarray([False, False, False, True, True])>>>x[mask]=-1>>>xarray([ 0, 1, 2, -1, -1])
Array that suppressed values indicated by a mask:
>>>x=np.ma.masked_array([np.nan,2,np.nan],[True,False,True])>>>xmasked_array(data = [-- 2.0 --], mask = [ True False True], fill_value = 1e+20)>>>x+[1,2,3]masked_array(data = [-- 4.0 --], mask = [ True False True], fill_value = 1e+20)
Masked arrays are often used when operating on arrays containingmissing or invalid entries.
A 2-dimensional ndarray that preserves its two-dimensional naturethroughout operations. It has certain special operations, such as*(matrix multiplication) and** (matrix power), defined:
>>>x=np.mat([[1,2],[3,4]])>>>xmatrix([[1, 2], [3, 4]])>>>x**2matrix([[ 7, 10], [15, 22]])
A function associated with an object. For example, each ndarray has amethod calledrepeat:
>>>x=np.array([1,2,3])>>>x.repeat(2)array([1, 1, 2, 2, 3, 3])
np.recarray and whose dtype is of typenp.record,making the fields of its data type to be accessible by attribute.a is a reference tob, then(aisb)==True. Therefore,a andb are different names for the same Python object.A way to represent items in a N-dimensional array in the 1-dimensionalcomputer memory. In row-major order, the rightmost index “variesthe fastest”: for example the array:
[[1,2,3],[4,5,6]]
is represented in the row-major order as:
[1,2,3,4,5,6]
Row-major order is also known as the C order, as the C programminglanguage uses it. New NumPy arrays are by default in row-major order.
Often seen in method signatures,self refers to the instanceof the associated class. For example:
>>>classPaintbrush(object):...color='blue'......defpaint(self):...print("Painting the city%s!"%self.color)...>>>p=Paintbrush()>>>p.color='red'>>>p.paint()# self refers to 'p'Painting the city red!
Used to select only certain elements from a sequence:
>>>x=range(5)>>>x[0, 1, 2, 3, 4]>>>x[1:3]# slice from 1 to 3 (excluding 3 itself)[1, 2]>>>x[1:5:2]# slice from 1 to 5, but skipping every second element[1, 3]>>>x[::-1]# slice a sequence in reverse[4, 3, 2, 1, 0]
Arrays may have more than one dimension, each which can be slicedindividually:
>>>x=np.array([[1,2],[3,4]])>>>xarray([[1, 2], [3, 4]])>>>x[:,1]array([2, 4])
A sequence that may contain a variable number of types of anykind. A tuple is immutable, i.e., once constructed it cannot bechanged. Similar to a list, it can be indexed and sliced:
>>>x=(1,'one',[1,2])>>>x(1, 'one', [1, 2])>>>x[0]1>>>x[:2](1, 'one')
A useful concept is “tuple unpacking”, which allows variables tobe assigned to the contents of a tuple:
>>>x,y=(1,2)>>>x,y=1,2
This is often used when a function returns multiple values:
>>>defreturn_many():...return1,'alpha',None
>>>a,b,c=return_many()>>>a,b,c(1, 'alpha', None)
>>>a1>>>b'alpha'
add,sin andlogical_or.An array that does not own its data, but refers to another array’sdata instead. For example, we may create a view that only showsevery second element of another array:
>>>x=np.arange(5)>>>xarray([0, 1, 2, 3, 4])>>>y=x[::2]>>>yarray([0, 2, 4])>>>x[0]=3# changing x changes y as well, since y is a view on x>>>yarray([3, 2, 4])
Python is a high-level (highly abstracted, or English-like) language.This abstraction comes at a price in execution speed, and sometimesit becomes necessary to use lower level languages to do fastcomputations. A wrapper is code that provides a bridge betweenhigh and the low level languages, allowing, e.g., Python to executecode written in C or Fortran.
Examples include ctypes, SWIG and Cython (which wraps C and C++)and f2py (which wraps Fortran).