Basics Flashcards
Import numpy
import numpy as np
ndarray vs python list
NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types
Ndarray
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.
Number of axes (dimensions)
ndarray.ndim
the number of axes (dimensions) of the array.
Dimentions size
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim.
ndarray.shape
the total number of elements of the array.
ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.
Data type of elements
ndarray.dtype
an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.
Size in bytes of each element of the array
ndarray.itemsize
the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.
Creating arr
you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences.
Zeros, Ones, Empty
The function zeros creates an array full of zeros, the function ones creates an array full of ones, and the function empty creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is float64, but it can be specified via the key word argument dtype.
N-d array
array transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.
Aarange
NumPy provides the arange function which is analogous to the Python built-in range, but returns an array.
Prinitng array
Note reahape(row, colum)
Ariphmetic operations substract
(elementwise)
a = np.array([20, 30, 40, 50]) b = np.arange(4) b array([0, 1, 2, 3]) c = a - b c array([20, 29, 38, 47])
Ariphmetic operations square
(elementwise)
a = np.array([20, 30, 40, 50]) b = np.arange(4) b array([0, 1, 2, 3]) c = a**b c array([0, 1, 4, 9])