NumPy: Arrays - Overview NumPy (Numerical Python) is a ...

NumPy: Arrays - Overview ? NumPy (Numerical Python) is a scientific package for Python ? The primary object it addresses is the ND array (class ndarray) ? Like most other languages, NumPy arrays are homogeneous: they hold values

of the same data type ? NumPy has its own data types (that correspond to standard Python data

types) ? The standard Python data types can be used interchangeably with the NumPy data types

? To use NumPy, the standard usage is import numpy as np

? A dimension is referred to as an axis

1

NumPy: Arrays - Creation

? There are numerous ways to create an array in NumPy

1. Using a constructor ? Syntax: np.array(shape [comma separated option list]) (array is an alias for ndarray) ? Shape can take the form of A tuple of dimensions; e.g., (2, 3) An array literal; e.g. [ [7, 3, 5], [3, 9, 6] ] ? The data type is inferred from the values provided in the argument to the constructor; by default the type is float64 The type can be explicitly indicated using the dtype = type option: np.ndarray( [ [7, 3, 5], [3, 9, 6] ], dtype = int16)

2. Using specialized constructors ? zeros: Creates an array of zeroes ? ones: Creates an array of ones ? empty: Creates an an empty array whose values are undefined ? eye(n): Creates an identity matrix of dimensions n ? n ? identity(n): Same as eye() ? full(shape, fill value): Creates an array of specified dimensions all of whose elements are fill value

3. Using the arange function ? Syntax: arange(start value, end value, step) ? Create a 1D array (vector) whose first element is start value, last element is end value, with intermediate elements start value+step, start value+ 2 step, etc. ? When using floats, it is recommended that linspace() is used instead Its third argument specifies the number of elements in the array, rather than the step size

? Reshaping

? The reshape method allows changing the dimensions of an array Syntax: ndarray.reshape(dimension tuple)

? The ravel method flattens an array Syntax: ndarray.ravel()

? Both of the above return copies and do not affect the original

2

NumPy: Arrays - Accessing Elements ? Single array elements are indicated by a single pair of square brackets enclosing

a comma-separated list of indices ? Slicing works the same as for other Python sequences

>>> a array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]) >>> a[2] 8 >>> a[2:5] array([ 8, 27, 64]) >>> b array([[ 0, 1, 2, 3],

[10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]]) >>> b[2,3] 23 >>> b[0:5, 1] array([ 1, 11, 21, 31, 41]) >>> b[ : ,1] array([ 1, 11, 21, 31, 41]) >>> b[1:3, : ] array([[10, 11, 12, 13], [20, 21, 22, 23]])

3

NumPy: Arrays - Display ? For 1D and 2D arrays, the display is obvious:

>>> v = np.array([1, 2, 3]) >>> v array([1, 2, 3] >>> m = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) >>> m array([[ 1, 2, 3, 4],

[ 5, 6, 7, 8]]

? For nD arrays, maybe not so:

>>> a = np.array([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 1 >>> a array([[[ 1, 2, 3, 4],

[ 5, 6, 7, 8], [ 9, 10, 11, 12]],

[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]])

? This creates a 2 ? 3 ? 4 array ? The outer level represents the number of rows (there are 2); the next the

number of columns (3), and the innermost the depth (4) ? The first row, first column has the values 1, 2, 3, 4 from front to back ? As displayed, the top block of values represents the top plane of the array,

the second the bottom plane ? If each plane were rotated 90 degrees, it would more accurately reflect the

3D nature of the array; i.e., the first column of the top plane holds the values 1 - 4, the second column the values 5 - 8, and the third column 9 - 12

4

NumPy: Arrays - Attributes ? ndarray.ndim the number of axes (dimensions) of the array. ? ndarray.shape the actual dimensions of the array. This is a tuple of integers

indicating the size of the array in each dimension. ? ndarray.size the total number of elements of the array. This is equal to the

product of the elements of shape. ? ndarray.dtype an object describing the type of the elements in the array.

5

NumPy: Arrays - Operators, Functions, and Methods

? Arithmetic operations

? These are applied on an element-by-element basis when both arguments are arrays and a copy is returned in most cases

? If one argument is a scalar, it is applied on an element-by-element basis to the array and a copy is returned in most cases

? Some obviously affect the original (e.g., +=) ? Broadcasting

In general, arrays must have the same dimensions for arithmetic operations to apply

In some cases (e.g., when one operand is a scalar), operations on differentlysized arrays is permitted

This is called broadcasting (See documentation for details)

? Methods

? ndarray.astype(dtype) returns a copy cast to dtype ? ndarray.copy() returns a copy ? ndarray.diagonal() returns the diagonal ? ndarray.dot(b) returns the dot product with b ? ndarray.fill(value) fills array with scalar value value ? ndarray.max(a [, axis = n]) returns max value of array or along axis n ? ndarray.mean(a [, axis = n]) returns average value of array or along axis n ? ndarray.min(a [, axis = n]) returns min value of array or along axis n ? ndarray.prod(a [, axis = n]) returns product of array elements or elements

along axis n ? ndarray.sort(a [, axis = n]) sort array or elements along axis n in place ? ndarray.std(a [, axis = n]) returns standard deviation of array elements or

elements along axis n ? ndarray.sum(a [, axis = n]) returns sum of array elements or elements along

axis n ? ndarray.trace(a [, axis = n]) returns sum of diagonal array elements ? ndarray.var(a [, axis = n]) variance of array elements or elements along

axis n

6

NumPy: Arrays - Operators, Functions, and Methods (2) ? Matrix operations

? ndarray.transpose() returns the transpose ? ndarray.linalg.inv(a) returns the inverse of a ? a1 @ a2 matrix multiplication (a1 dot a2) ? Statistics (Range functions) (Universal functions (i.e., class functions)) ? numpy.amin(a [, axis = n]) returns min value of array or along axis n ? numpy.amax(a [, axis = n]) returns max value of array or along axis n ? numpy.sum(a [, axis = n]) returns sum of array elements or elements along

axis n ? numpy.prod(a [, axis = n]) returns product of array elements or elements

along axis n

7

NumPy: Arrays - Structured Arrays and Record Arrays ? Structured arrays and record arrays are conceptually the same:

? They are 1D arrays of tuples that allow access of entries using a key ? Think of them as representing columns of a spreadsheet, where the column

headings represent the key ? Each value in a tuple represents a value in the corresponding column ? Specifying a key returns a 1D array of values from that corresponding col-

umn ? Structured arrays:

? These are regular nd arrays with the addition of the column data ? Syntax: Regular declaration of 1D array of tuples with dtype = np.dtype([(key,

type)[, (key, type)] ...]) where there is one (key, type) tuple for each column in the array ? Example: >>> a1=np.array([(4, 5.2, 1), (1, 2.1, 8), (10, 6.7, 0)],

dtype = np.dtype([('x', int), ('y', float), ('z', int)])) >>> a1['y'] array([5.2, 2.1, 6.7], dtype = float)

>>> x[1] (1, 2.1, 8) ? Record arrays ? These are a subclass of ndarray ? Syntax: same as for structured arrays except use recarray instead of array or ndarray ? They allow access using dot notation For example, a1.x if the above were defined as a recarray ? They tend to be slower than structured arrays

8

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download