Python Num Py Tutorial - Numpy
Python Num Py Tutorial - Numpy
NumPy stands for numeric python which is a python package for the
computation and processing of the multidimensional and single
dimensional array elements.
What is NumPy
NumPy stands for numeric python which is a python package for the
computation and processing of the multidimensional and single
dimensional array elements.
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.
about:blank 1/53
16:49 09/05/2024 Python Num Py Tutorial - 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.
about:blank 2/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
2.
3. $ python-scipy python-matplotlibipythonipythonnotebook python-
pandas
4.
5. $ python-sympy python-nose
NumPy Ndarray
Ndarray is the n-dimensional array object defined in the numpy which
stores the collection of the similar type of elements. In other words, we
can define a ndarray as the collection of the data type (dtype) objects.
The ndarray object can be accessed by using the 0 based indexing. Each
element of the Array object contains the same size in the memory.
1. >>> a = numpy.array
We can also pass a collection object into the array routine to create the
equivalent n-dimensional array. The syntax is given below.
about:blank 3/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
S Paramete Description
N r
about:blank 4/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
To change the data type of the array elements, mention the name of the
data type along with the collection.
about:blank 5/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
Output:
Example
about:blank 6/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Output:
Example
1. import numpy as np
2. a = np.array([[1,2,3,4,5,6,7]])
3. print("Array Size:",a.size)
4. print("Shape:",a.shape)
Output:
Array Size: 7
Shape: (1, 7)
about:blank 7/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2. a = np.array([[1,2],[3,4],[5,6]])
3. print("printing the original array..")
4. print(a)
5. a=a.reshape(2,3)
6. print("printing the reshaped array..")
7. print(a)
Output:
Example
1. import numpy as np
2. a = np.array([[1,2],[3,4],[5,6]])
3. print(a[0,1])
4. print(a[2,0])
Output:
2
5
The above program prints the 2nd element from the 0th index and
0th element from the 2nd index of the array.
Linspace
about:blank 8/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
The linspace() function returns the evenly spaced values over the given
interval. The following example returns the 10 evenly separated values
over the given interval 5-15
Example
1. import numpy as np
2. a=np.linspace(5,15,10) #prints 10 values which are evenly spaced o
ver the given interval 5-15
3. print(a)
Output:
Example
1. import numpy as np
2. a = np.array([1,2,3,10,15,4])
3. print("The array:",a)
4. print("The maximum element:",a.max())
5. print("The minimum element:",a.min())
6. print("The sum of the elements:",a.sum())
Output:
The array: [ 1 2 3 10 15 4]
The maximum element: 15
The minimum element: 1
The sum of the elements: 35
about:blank 9/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. print("The array:",a)
4. print("The maximum elements of columns:",a.max(axis = 0))
5. print("The minimum element of rows",a.min(axis = 1))
6. print("The sum of all rows",a.sum(axis = 1))
Output:
Standard deviation means how much each element of the array varies
from the mean value of the numpy array.
about:blank 10/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. print(np.sqrt(a))
4. print(np.std(a))
Output:
Example
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. b = np.array([[1,2,3],[12, 19, 29]])
4. print("Sum of array a and b\n",a+b)
5. print("Product of array a and b\n",a*b)
6. print("Division of array a and b\n",a/b)
Array Concatenation
The numpy provides us with the vertical stacking and horizontal stacking
which allows us to concatenate two multi-dimensional arrays vertically or
horizontally.
Example
about:blank 11/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
1. import numpy as np
2. a = np.array([[1,2,30],[10,15,4]])
3. b = np.array([[1,2,3],[12, 19, 29]])
4. print("Arrays vertically concatenated\n",np.vstack((a,b)));
5. print("Arrays horizontally concatenated\n",np.hstack((a,b)))
Output:
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.
about:blank 12/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
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.
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.
Align: It can be set to any boolean value. If true, then it adds extra
padding to make it equivalent to a C struct.
about:blank 13/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example 1
1. import numpy as np
2. d = np.dtype(np.int32)
3. print(d)
Output:
int32
Example 2
1. import numpy as np
2. d = np.int32(i4)
3. print(d)
Output:
int32
Example 1
1. import numpy as np
2. d = np.dtype([('salary',np.float)])
3. print(d)
Output:
Example 2
1. import numpy as np
2. d=np.dtype([('salary',np.float)])
3. arr = np.array([(10000.12,),(20000.50,)],dtype=d)
4. print(arr['salary'])
about:blank 14/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Output:
Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized
array of specified shape and data type.
o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F
for FORTRAN-style column-major order.
Example
1. import numpy as np
2. arr = np.empty((3,2), dtype = int)
3. 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.
about:blank 15/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F
for FORTRAN-style column-major order.
Example
1. import numpy as np
2. arr = np.zeros((3,2), dtype = int)
3. 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.
Example
1. import numpy as np
2. arr = np.ones((3,2), dtype = int)
3. print(arr)
Output:
[[1 1]
[1 1]
[1 1]]
about:blank 16/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
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.
Output:
<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]
Output:
<class 'numpy.ndarray'>
about:blank 17/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
[1 2 3 4 5 6 7]
Output:
<class 'numpy.ndarray'>
[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9])]
numpy.frombuffer
This function is used to create an array by using the specified buffer. The
syntax to use this buffer is given below.
o dtype: It represents the data type of the returned data type array. The
default value is 0.
o count: It represents the length of the returned ndarray. The default value
is -1.
o offset: It represents the starting position to read from. The default value
is 0.
Example
1. import numpy as np
2. l = b'hello world'
3. print(type(l))
4. a = np.frombuffer(l, dtype = "S1")
5. print(a)
6. print(type(a))
Output:
<class 'bytes'>
about:blank 18/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']
<class 'numpy.ndarray'>
numpy.fromiter
This routine is used to create a ndarray by using an iterable object. It
returns a one-dimensional ndarray object.
Example
1. import numpy as np
2. list = [0,2,4,6]
3. it = iter(list)
4. x = np.fromiter(it, dtype = float)
5. print(x)
6. print(type(x))
Output:
[0. 2. 4. 6.]
<class 'numpy.ndarray'>
Numpy.arrange
It creates an array by using the evenly spaced values over the given
interval. The syntax to use the function is given below.
about:blank 19/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
group
Example
1. import numpy as np
2. arr = np.arange(0,10,2,float)
3. print(arr)
Output:
[0. 2. 4. 6. 8.]
Example
1. import numpy as np
2. arr = np.arange(10,100,5,int)
3. print("The array over the given range is ",arr)
Output:
NumPy.linspace
It is similar to the arrange function. However, it doesn?t allow us to specify
the step size in the syntax.
about:blank 20/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
4. endpoint: Its true value indicates that the stopping value is included in
the interval.
5. rettstep: This has to be a boolean value. Represents the steps and
samples between the consecutive numbers.
6. dtype: It represents the data type of the array items.
Example
1. import numpy as np
2. arr = np.linspace(10, 20, 5)
3. print("The array over the given range is ",arr)
Output:
The array over the given range is [10. 12.5 15. 17.5 20.]
Example
1. import numpy as np
2. arr = np.linspace(10, 20, 5, endpoint = False)
3. print("The array over the given range is ",arr)
Output:
The array over the given range is [10. 12. 14. 16. 18.]
numpy.logspace
It creates an array by using the numbers that are evenly separated on a
log scale.
about:blank 21/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2. arr = np.logspace(10, 20, num = 5, endpoint = True)
3. print("The array over the given range is ",arr)
Output:
Example
1. import numpy as np
2. arr = np.logspace(10, 20, num = 5,base = 2, endpoint = True)
3. print("The array over the given range is ",arr)
Output:
NumPy Broadcasting
In Mathematical operations, we may need to consider the arrays of
different shapes. NumPy can perform such operations where the array of
different shapes are involved.
Example
1. import numpy as np
2. a = np.array([1,2,3,4,5,6,7])
3. b = np.array([2,4,6,8,10,12,14])
4. c = a*b;
about:blank 22/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
5. print(c)
Output:
[ 2 8 18 32 50 72 98]
Example
1. import numpy as np
2. a = np.array([1,2,3,4,5,6,7])
3. b = np.array([2,4,6,8,10,12,14,19])
4. c = a*b;
5. print(c)
Output:
ValueError: operands could not be broadcast together with shapes (7,) (8,)
In the above example, we can see that the shapes of the two arrays are
not similar and therefore they cannot be multiplied together. NumPy can
perform such operation by using the concept of broadcasting.
Broadcasting Rules
Broadcasting is possible if the following cases are satisfied.
1. The smaller dimension array can be appended with '1' in its shape.
2. Size of each output dimension is the maximum of the input sizes in the
dimension.
about:blank 23/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
2. Arrays have the same number of dimensions, and the length of each
dimension is either a common length or 1.
3. Array with the fewer dimension can be appended with '1' in its shape.
Example
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. b = np.array([2,4,6,8])
4. print("\nprinting array a..")
5. print(a)
6. print("\nprinting array b..")
7. print(b)
8. print("\nAdding arrays a and b ..")
9. c = a + b;
10. print(c)
Output:
about:blank 24/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. print("Printing array:")
4. print(a);
5. print("Iterating over the array:")
6. for x in np.nditer(a):
7. 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
1. import numpy as np
2. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. print("Printing the array:")
4. print(a)
5. print("Printing the transpose of the array:")
6. at = a.T
7. print(at)
8.
9. #this will be same as previous
10. for x in np.nditer(at):
11. print(print("Iterating over the array:")
about:blank 25/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
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
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the array:\n")
6.
7. print(a)
8.
9. print("\nPrinting the transpose of the array:\n")
10. at = a.T
11.
12. print(at)
13.
14. print("\nIterating over the transposed array\n")
15.
16. for x in np.nditer(at):
about:blank 26/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
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]
about:blank 27/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
[ 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
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the array:\n")
6.
7. print(a)
8.
9. print("\nPrinting the transpose of the array:\n")
10. at = a.T
11.
12. print(at)
13.
14. print("\nIterating over the transposed array\n")
15.
16. for x in np.nditer(at):
17. print(x, end= ' ')
18.
19. print("\nSorting the transposed array in C-style:\n")
20.
21. print("\nIterating over the C-style array:\n")
22. for x in np.nditer(at, order = 'C'):
23. print(x,end=' ')
Output:
1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:
about:blank 28/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
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
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the original array:\n")
6.
7. print(a)
8.
9. print("\nIterating over the modified array\n")
10.
11. for x in np.nditer(a, op_flags = ['readwrite']):
12. x[...] = 3 * x;
13. 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
S Operator Description
N
about:blank 29/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
1 bitwise_a It is used to calculate the bitwise and operation between the corresponding
nd array elements.
3 invert It is used to calculate the bitwise not the operation of the array elements.
4 left_shift It is used to shift the bits of the binary representation of the elements to
the left.
5 right_shift It is used to shift the bits of the binary representation of the elements to
the right.
bitwise_and Operation
The NumPy provides the bitwise_and() function which is used to calculate
the bitwise_and operation of the two operands.
Example
1. import numpy as np
2.
3. a = 10
4. b = 12
5.
6. print("binary representation of a:",bin(a))
7. print("binary representation of b:",bin(b))
8. print("Bitwise-and of a and b: ",np.bitwise_and(a,b))
Output:
about:blank 30/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
The output of the AND result of the two bits is 1 if and only if both the bits
are 1 otherwise it will be 0.
A B AND (A, B)
0 0 0
0 1 0
1 0 0
1 1 1
bitwise_or Operator
The NumPy provides the bitwise_or() function which is used to calculate
the bitwise or operation of the two operands.
Example
1. import numpy as np
2.
3. a = 50
4. b = 90
5. print("binary representation of a:",bin(a))
6. print("binary representation of b:",bin(b))
7. print("Bitwise-or of a and b: ",np.bitwise_or(a,b))
Output:
Or truth table
The output of the OR result of the two bits is 1 if one of the bits are 1
otherwise it will be 0.
about:blank 31/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
A B Or (A, B)
0 0 0
0 1 1
1 0 1
1 1 1
Invert operation
It is used to calculate the bitwise not the operation of the given operand.
The 2's complement is returned if the signed integer is passed in the
function.
Example
1. import numpy as np
2.
3. arr = np.array([20],dtype = np.uint8)
4. print("Binary representation:",np.binary_repr(20,8))
5.
6. print(np.invert(arr))
7.
8. print("Binary representation: ", np.binary_repr(235,8))
Output:
It shifts the bits in the binary representation of the operand to the left by
the specified position. An equal number of 0s are appended from the right.
Consider the following example.
Example
1. import numpy as np
2.
about:blank 32/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Output:
Example
1. import numpy as np
2.
3. print("left shift of 20 by 3 bits",np.right_shift(20, 3))
4.
5. print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
6.
7. print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))
Output:
S Function Description
N
about:blank 33/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
2 multiply( It returns the multiple copies of the specified string, i.e., if a string 'hello' is
) multiplied by 3 then, a string 'hello hello' is returned.
3 center() It returns the copy of the string where the original string is centered with
the left and right padding filled with the specified number of fill characters.
4 capitalize It returns a copy of the original string in which the first letter of the origina
() string is converted to the Upper Case.
5 title() It returns the title cased version of the string, i.e., the first letter of each
word of the string is converted into the upper case.
6 lower() It returns a copy of the string in which all the letters are converted into the
lower case.
7 upper() It returns a copy of the string in which all the letters are converted into the
upper case.
9 splitlines( It returns the list of lines in the string, breaking at line boundaries.
)
10 strip() Returns a copy of the string with the leading and trailing white spaces
removed.
11 join() It returns a string which is the concatenation of all the strings specified in
the given sequence.
13 decode() It is used to decode the specified string element-wise using the specified
codec.
about:blank 34/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Output:
Output:
Output:
Padding the string through left and right with the fill char *
*****Javatpoint*****
Output:
Output:
about:blank 35/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Welcome To Javatpoint
Output:
Output:
Output:
Output:
about:blank 36/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Output:
Output:
H:M
Output:
Output:
b'\xa6\x85\x93\x83\x96\x94\x85@\xa3\x96@\x91\x81\xa5\x81\xa3\x97\x96\x89\x9
5\xa3'
welcome to javatpoint
about:blank 37/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Trigonometric functions
Numpy contains the trigonometric functions which are used to calculate
the sine, cosine, and tangent of the different angles in radian.
The sin, cos, and tan functions return the trigonometric ratio for the
specified angles. Consider the following example.
Example
1. import numpy as np
2. arr = np.array([0, 30, 60, 90, 120, 150, 180])
3. print("\nThe sin value of the angles",end = " ")
4. print(np.sin(arr * np.pi/180))
5. print("\nThe cosine value of the angles",end = " ")
6. print(np.cos(arr * np.pi/180))
7. print("\nThe tangent value of the angles",end = " ")
8. print(np.tan(arr * np.pi/180))
Output:
On the other hand, arcsin(), arccos(), and arctan() functions return the
trigonometric inverse of the specified angles.
Example
1. import numpy as np
2. arr = np.array([0, 30, 60, 90])
3. print("printing the sin values of different angles")
about:blank 38/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
4.
5. sinval = np.sin(arr*np.pi/180)
6.
7. print(sinval)
8. print("printing the inverse of the sin")
9. cosec = np.arcsin(sinval)
10.
11. print(cosec)
12.
13. print("printing the values in degrees")
14. print(np.degrees(cosec))
15.
16. print("\nprinting the cos values of different angles")
17. cosval = np.cos(arr*np.pi/180)
18.
19. print(cosval)
20. print("printing the inverse of the cos")
21. sec = np.arccos(cosval)
22. print(sec)
23.
24. print("\nprinting the values in degrees")
25. print(np.degrees(sec))
26.
27. print("\nprinting the tan values of different angles")
28. tanval = np.tan(arr*np.pi/180)
29.
30. print(tanval)
31. print("printing the inverse of the tan")
32. cot = np.arctan(tanval)
33. print(cot)
34.
35. print("\nprinting the values in degrees")
36. print(np.degrees(cot))
Output:
about:blank 39/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Rounding Functions
The numpy provides various functions that can be used to truncate the
value of a decimal float number rounded to a particular precision of
decimal numbers. Let's discuss the rounding functions.
1. numpy.around(num, decimals)
S Parameter Description
N
about:blank 40/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print("printing the original array values:",end = " ")
4. print(arr)
5. print("Array values rounded off to 2 decimal position",np.around(arr, 2))
6. print("Array values rounded off to -1 decimal position",np.around(arr, -1))
Output:
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.floor(arr))
Output:
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.ceil(arr))
Output:
about:blank 41/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("The original array:\n")
6. print(a)
7.
8.
9. print("\nThe minimum element among the array:",np.amin(a))
10. print("The maximum element among the array:",np.amax(a))
11.
12. print("\nThe minimum element among the rows of array",np.amin(a,0))
13. print("The maximum element among the rows of array",np.amax(a,0))
14.
15. print("\nThe minimum element among the columns of array",np.amin(a,1)
)
16. print("The maximum element among the columns of array",np.amax(a,1))
Output:
Advertisement
[[ 2 10 20]
about:blank 42/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
[80 43 31]
[22 43 10]]
numpy.ptp() function
The name of the function numpy.ptp() is derived from the name peak-to-
peak. It is used to return the range of values along an axis. Consider the
following example.
Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("Original array:\n",a)
6.
7. print("\nptp value along axis 1:",np.ptp(a,1))
8.
9. print("ptp value along axis 0:",np.ptp(a,0))
Output:
Original array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]
numpy.percentile() function
The syntax to use the function is given below.
1. numpy.percentile(input, q, axis)
about:blank 43/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2.
3. a = np.array([[2,10,20],[80,43,31],[22,43,10]])
4.
5. print("Array:\n",a)
6.
7. print("\nPercentile along axis 0",np.percentile(a, 10,0))
8.
9. print("Percentile along axis 1",np.percentile(a, 10, 1))
Output:
Array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]
about:blank 44/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2.
3. a = np.array([[1,2,3],[4,5,6],[7,8,9]])
4.
5. print("Array:\n",a)
6.
7. print("\nMedian of array along axis 0:",np.median(a,0))
8. print("Mean of array along axis 0:",np.mean(a,0))
9. print("Average of array along axis 1:",np.average(a,1))
The kind of the sorting algorithm to be used in the sort operation must be
mentioned in the function call.
1 Quick Sort O (n ^ 2)
about:blank 45/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
S Parameter Description
N
2 axis It represents the axis along which the array is to be sorted. If the axis is
not mentioned, then the sorting is done along the last available axis.
4 order It represents the filed according to which the array is to be sorted in the
case if the array contains the fields.
Example
1. import numpy as np
2.
3. a = np.array([[10,2,3],[4,5,6],[7,8,9]])
4.
5. print("Sorting along the columns:")
6. print(np.sort(a))
7.
8. print("Sorting along the rows:")
9. print(np.sort(a, 0))
10.
11. data_type = np.dtype([('name', 'S10'),('marks',int)])
12.
13. arr = np.array([('Mukesh',200),('John',251)],dtype = data_type)
14.
15. print("Sorting data ordered by name")
16.
17. print(np.sort(arr,order = 'name'))
Output:
about:blank 46/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
[ 4 5 6]
[ 7 8 9]]
Sorting along the rows:
[[ 4 2 3]
[ 7 5 6]
[10 8 9]]
Sorting data ordered by name
[(b'John', 251) (b'Mukesh', 200)]
numpy.argsort() function
This function is used to perform an indirect sort on an input array that is, it
returns an array of indices of data which is used to construct the array of
sorted data.
Example
1. import numpy as np
2.
3. a = np.array([90, 29, 89, 12])
4.
5. print("Original array:\n",a)
6.
7. sort_ind = np.argsort(a)
8.
9. print("Printing indices of sorted data\n",sort_ind)
10.
11. sort_a = a[sort_ind]
12.
13. print("printing sorted array")
14.
15. for i in sort_ind:
16. print(a[i],end = " ")
Output:
Original array:
[90 29 89 12]
Printing indices of sorted data
[3 1 2 0]
printing sorted array
12 29 89 90
about:blank 47/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
numpy.lexsort() function
This function is used to sort the array using the sequence of keys
indirectly. This function performs similarly to the numpy.argsort() which
returns the array of indices of sorted data.
Example
1. import numpy as np
2.
3. a = np.array(['a','b','c','d','e'])
4.
5. b = np.array([12, 90, 380, 12, 211])
6.
7. ind = np.lexsort((a,b))
8.
9. print("printing indices of sorted data")
10.
11. print(ind)
12.
13. print("using the indices to sort the array")
14.
15. for i in ind:
16. print(a[i],b[i])
Output:
numpy.nonzero() function
This function is used to find the location of the non-zero elements from the
array.
about:blank 48/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Example
1. import numpy as np
2.
3. b = np.array([12, 90, 380, 12, 211])
4.
5. print("printing original array",b)
6.
7. print("printing location of the non-zero elements")
8.
9. print(b.nonzero())
Output:
numpy.where() function
This function is used to return the indices of all the elements which
satisfies a particular condition.
Example
1. import numpy as np
2.
3. b = np.array([12, 90, 380, 12, 211])
4.
5. print(np.where(b>12))
6.
7. c = np.array([[20, 24],[21, 23]])
8.
9. print(np.where(c>20))
Output:
(array([1, 2, 4]),)
(array([0, 1, 1]), array([1, 0, 1]))
about:blank 49/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
The copy of an input array is physically stored at some other location and
the content stored at that particular location is returned which is the copy
of the input array whereas the different view of the same memory location
is returned in the case of view.
In this section of the tutorial, we will consider the way by which, the
different copies and views are generated from some memory location.
Array Assignment
The assignment of a numpy array to another array doesn't make the
direct copy of the original array, instead, it makes another array with the
same content and same id. It represents the reference to the original
array. Changes made on this reference are also reflected in the original
array.
The id() function returns the universal identifier of the array similar to the
pointer in C.
Advertisement
Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b=a
10.
11. print("\nmaking copy of the array a")
12.
13. print("\nID of b:",id(b))
14.
15. b.shape = 4,3;
16.
17. print("\nChanges on b also reflect to a:")
18. print(a)
about:blank 50/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
ID of array a: 139663602288640
ID of b: 139663602288640
ndarray.view() method
The ndarray.view() method returns the new array object which contains
the same content as the original array does. Since it is a new array object,
changes made on this object do not reflect the original array.
Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b = a.view()
10.
11. print("\nID of b:",id(b))
12.
13. print("\nprinting the view b")
14. print(b)
15.
16. b.shape = 4,3;
17.
18. print("\nChanges made to the view b do not reflect a")
about:blank 51/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
ID of array a: 140280414447456
ID of b: 140280287000656
Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
view
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]
ndarray.copy() method
It returns the deep copy of the original array which doesn't share any
memory with the original array. The modification made to the deep copy
of the original array doesn't reflect the original array.
Example
1. import numpy as np
2.
3. a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
4.
5. print("Original Array:\n",a)
6.
7. print("\nID of array a:",id(a))
8.
9. b = a.copy()
about:blank 52/53
16:49 09/05/2024 Python Num Py Tutorial - numpy
10.
11. print("\nID of b:",id(b))
12.
13. print("\nprinting the deep copy b")
14. print(b)
15.
16. b.shape = 4,3;
17.
18. print("\nChanges made to the copy b do not reflect a")
19. print("\nOriginal array \n",a)
20. print("\nCopy\n",b)
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
ID of array a: 139895697586176
ID of b: 139895570139296
Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
Copy
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]
about:blank 53/53