Professional Documents
Culture Documents
NumPy stands for numeric python which is a python package for the computation and
processing of the multidimensional and single dimensional array elements.
Skip Ad
NumPy provides a convenient and efficient way to handle the vast amount of data.
NumPy is also very convenient with Matrix multiplication and data reshaping. NumPy is
fast which makes it reasonable to work with a large set of data.
There are the following advantages of using NumPy for data analysis.
1. $ pip install numpy
It is best practice to install NumPy with the full SciPy stack. The binary distribution of the
SciPy stack is specific to the operating systems.
Windows
On the Windows operating system, The SciPy stack is provided by the Anaconda which
is a free distribution of the Python SciPy package.
The CanoPy also comes with the full SciPy stack which is available as free as well as
commercial license. We can download it by visiting the link:
https://www.enthought.com/products/canopy/
The Python (x, y) is also available free with the full SciPy distribution. Download it by
visiting the link: https://python-xy.github.io/
Linux
In Linux, the different package managers are used to install the SciPy stack. The package
managers are specific to the different distributions of Linux. Let's look at each one of
them.
Ubuntu
Execute the following command on the terminal.
1. $ sudo apt-get install python-numpy
2.
1 bool_ It represents the boolean value indicating true or false. It is stored as a byte.
2 int_ It is the default type of integer. It is identical to long type in C that contains 64
bit or 32-bit integer.
5 int8 It is the 8-bit integer identical to a byte. The range of the value is -128 to 127.
14 float16 It is the half-precision float. 5 bits are reserved for the exponent. 10 bits are
reserved for mantissa, and 1 bit is reserved for the sign.
15 float32 It is a single precision float. 8 bits are reserved for the exponent, 23 bits are
reserved for mantissa, and 1 bit is reserved for the sign.
16 float64 It is the double precision float. 11 bits are reserved for the exponent, 52 bits are
reserved for mantissa, 1 bit is used for the sign.
18 complex64 It is used to represent the complex number where real and imaginary part
shares 32 bits each.
19 complex12 It is used to represent the complex number where real and imaginary part
8 shares 64 bits each.
3. $ python-scipy python-matplotlibipythonipythonnotebook python-pandas
4.
5. $ python-sympy python-nose
Redhat
On Redhat, the following commands are executed to install the Python SciPy package
stack.
1. $ sudo yum install numpyscipy python-matplotlibipython
2.
3. $ python-pandas sympy python-nose atlas-devel
To verify the installation, open the Python prompt by executing python command on
the terminal (cmd in the case of windows) and try to import the module NumPy as
shown in the below image. If it doesn't give the error, then it is installed successfully.
NumPy Datatypes
The NumPy provides a higher range of numeric data types than that provided by the
Python. A list of numeric data types is given in the following table.
NumPy dtype
All the items of a numpy array are data type objects also known as numpy dtypes. A
data type object implements the fixed size of memory corresponding to an array.
1. numpy.dtype(object, align, copy)
Keep Watching
Align: It can be set to any boolean value. If true, then it adds extra padding to make it
equivalent to a C struct.
Example 1
import numpy as np
d = np.dtype(np.int32)
print(d)
Output:
int32
Example 2
import numpy as np
d = np.int32(i4)
print(d)
Output:
int32
Example 1
import numpy as np
d = np.dtype([('salary',np.float)])
print(d)
Output:
Example 2
import numpy as np
d=np.dtype([('salary',np.float)])
arr = np.array([(10000.12,),(20000.50,)],dtype=d)
print(arr['salary'])
Output:
Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized array of
specified shape and data type.
1. numpy.empty(shape, dtype = float, order = 'C')
Example
import numpy as np
arr = np.empty((3,2), dtype = int)
print(arr)
Output:
[[ 140482883954664 36917984]
[ 140482883954648 140482883954648]
[6497921830368665435 172026472699604272]]
NumPy.Zeros
This routine is used to create the numpy array with the specified shape where each
numpy array item is initialized to 0.
1. numpy.zeros(shape, dtype = float, order = 'C')
Example
import numpy as np
arr = np.zeros((3,2), dtype = int)
print(arr)
Output:
[[0 0]
[0 0]
[0 0]]
NumPy.ones
This routine is used to create the numpy array with the specified shape where each
numpy array item is initialized to 1.
1. numpy.ones(shape, dtype = none, order = 'C')
Example
import numpy as np
arr = np.ones((3,2), dtype = int)
print(arr)
Output:
[[1 1]
[1 1]
[1 1]]
numpy.asarray
This routine is used to create an array by using the existing data in the form of lists, or
tuples. This routine is useful in the scenario where we need to convert a python
sequence into the numpy array object.
1. numpy.asarray(sequence, dtype = None, order = None)
1. sequence: It is the python sequence which is to be converted into the python array.
2. dtype: It is the data type of each item of the array.
3. order: It can be set to C or F. The default is C.
Output:
<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]
Output:
<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]
Output:
<class 'numpy.ndarray'>
[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9])]
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing array:")
print(a);
print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
Output:
Printing array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Iterating over the array:
1 2 3 4 2 4 5 6 10 20 39 3
Order of the iteration doesn't follow any special ordering like row-major or column-
order. However, it is intended to match the memory layout of the array.
Let's iterate over the transpose of the array given in the above example.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing the array:")
print(a)
print("Printing the transpose of the array:")
at = a.T
print(at)
#this will be same as previous
for x in np.nditer(at):
print(print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
Output:
Order of Iteration
As we know, there are two ways of storing values into the numpy arrays:
1. F-style order
2. C-style order
Let's see an example of how the numpy Iterator treats the specific orders (F or C).
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("\nPrinting the array:\n")
print(a)
print("\nPrinting the transpose of the array:\n")
at = a.T
print(at)
print("\nIterating over the transposed array\n")
for x in np.nditer(at):
print(x, end= ' ')
print("\nSorting the transposed array in C-style:\n")
c = at.copy(order = 'C')
print(c)
print("\nIterating over the C-style array:\n")
for x in np.nditer(c):
print(x,end=' ')
d = at.copy(order = 'F')
print(d)
print("Iterating over the F-style array:\n")
for x in np.nditer(d):
print(x,end=' ')
Output:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
1 2 10 2 4 20 3 5 39 4 6 3 [[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the F-style array:
1 2 3 4 2 4 5 6 10 20 39 3
We can mention the order 'C' or 'F' while defining the Iterator object itself. Consider the
following example.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("\nPrinting the array:\n")
print(a)
print("\nPrinting the transpose of the array:\n")
at = a.T
print(at)
print("\nIterating over the transposed array\n")
for x in np.nditer(at):
print(x, end= ' ')
print("\nSorting the transposed array in C-style:\n")
print("\nIterating over the C-style array:\n")
for x in np.nditer(at, order = 'C'):
print(x,end=' ')
Output:
1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:
1 2 10 2 4 20 3 5 39 4 6 3
However, we can set this flag to readwrite or write only to modify the array values.
Consider the following example.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("\nPrinting the original array:\n")
print(a)
print("\nIterating over the modified array\n")
for x in np.nditer(a, op_flags = ['readwrite']):
x[...] = 3 * x;
print(x,end = ' ')
Output:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
3 6 9 12 6 12 15 18 30 60 117 9
These are three methods through which we can perform numpy matrix multiplication.
1. First is the use of multiply() function, which perform element-wise multiplication of the
matrix.
2. Second is the use of matmul() function, which performs the matrix product of two arrays.
3. Last is the use of the dot() function, which performs dot product of two arrays.
In the output, a three-dimensional matrix has been shown whose elements are the result
of the element-wise multiplication of both array1 and array2 elements.
Output:
Output:
In the output, a three-dimensional matrix has been shown whose elements are the
product of both array1 and array2 elements.
o When both a and b are 1-D (one dimensional) arrays-> Inner product of two vectors
(without complex conjugation)
o When both a and b are 2-D (two dimensional) arrays -> Matrix multiplication
o When either a or b is 0-D (also known as a scalar) -> Multiply by using numpy.multiply(a,
b) or a * b.
o When a is an N-D array and b is a 1-D array -> Sum product over the last axis of a and b.
o When a is an N-D array and b is an M-D array provided that M>=2 -> Sum product over
the last axis of a and the second-to-last axis of b:
Also, dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
1. import numpy as np
2. array1=np.array([[1,2,3],[4,5,6],[7,8,9]],ndmin=3)
3. array2=np.array([[9,8,7],[6,5,4],[3,2,1]],ndmin=3)
4. result=np.dot(array1,array2)
5. result
In the output, a three-dimensional matrix has been shown whose elements are the dot
product of both array1 and array2 elements.
Output:
numpy.array() in Python
The homogeneous multidimensional array is the main object of NumPy. It is basically a
table of elements which are all of the same type and indexed by a tuple of positive
integers. The dimensions are called axis in NumPy.
The NumPy's array class is known as ndarray or alias array. The numpy.array is not the
same as the standard Python library class array.array. The array.array handles only one-
dimensional arrays and provides less functionality.
Syntax
1. numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
Parameters
There are the following parameters in numpy.array() function.
1) object: array_like
Skip Ad
Any object, which exposes an array interface whose __array__ method returns any nested
sequence or an array.
2) dtype : optional data-type
This parameter is used to define the desired parameter for the array element. If we do not define
the data type, then it will determine the type as the minimum type which will require to hold the
object in the sequence. This parameter is used only for upcasting the array.
3) copy: bool(optional)
If we set copy equals to true, the object is copied else the copy will be made when an object is a
nested sequence, or a copy is needed to satisfy any of the other requirements such as dtype,
order, etc.
The order parameter specifies the memory layout of the array. When the object is not an array,
the newly created array will be in C order (row head or row-major) unless 'F' is specified. When F
is specified, it will be in Fortran order (column head or column-major). When the object is an
array, it holds the following order.
'A' Unchanged When the input is F and not C then F order otherwise C order
When copy=False or the copy is made for the other reason, the result will be the same
as copy= True with some exceptions for A. The default order is 'K'.
5) subok : bool(optional)
When subok=True, then sub-classes will pass-through; otherwise, the returned array will
force to be a base-class array (default).
6) ndmin : int(optional)
This parameter specifies the minimum number of dimensions which the resulting array
should have. Users can be prepended to the shape as needed to meet this requirement.
Returns
The numpy.array() method returns an ndarray. The ndarray is an array object which
satisfies the specified requirements.
Example 1: numpy.array()
import numpy as np
arr=np.array([1,2,3])
arr
Output:
array([1, 2, 3])
Example 2:
import numpy as np
arr=np.array([1,2.,3.])
arr
Output:
In the output, an array has been displayed containing elements in such type which
require minimum memory to hold the object in the sequence.
import numpy as np
arr=np.array([[1,2.,3.],[4.,5.,7]])
arr
Output:
import numpy as np
arr=np.array([1,2.,3.],ndmin=2)
arr
Output:
import numpy as np
arr=np.array([12,45.,3.],dtype=complex)
arr
Output:
In the output, the values of the 'arr' elements have been shown in the form of complex
numbers.
import numpy as np
arr=np.array(np.mat('1 2;3 4'))
arr
arr=np.array(np.mat('1 2;3 4'),subok=True)
arr
Output:
array([[1, 2],
[3, 4]])
matrix([[1, 2],
[3, 4]])