Numpy For Mathematical Computing
Numpy For Mathematical Computing
Introduction to Numpy,
Numpy Array,
Numpy Mathematical Function,
Numpy Trigonometric Function,
Numpy random module,
Numpy String Operation.
NumPy (Numerical Python) is a fundamental library in Python for
numerical computing, particularly known for its efficient handling
of multi-dimensional arrays.
1. Introduction to NumPy:
Linear algebra: NumPy contains routines for linear algebra operations, such as
matrix multiplication, decompositions, and determinants.
import numpy as np
Creating NumPy Arrays
Using ndarray : The array object is called ndarray. NumPy arrays are created
using the array() function.
Example:
import numpy as np
# Creating a 1D array
x = np.array([1, 2, 3])
# Creating a 2D array
y = np.array([[1, 2], [3, 4]])
# Creating a 3D array
z = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(x)
print(y)
print(z)
Output
[1 2 3]
[[1 2]
[3 4]]
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Using Numpy Functions: NumPy provides convenient methods to create arrays
initialized with specific values like zeros and ones:
Example:
import numpy as np
print(a1_zeros)
print(a2_ones)
print(a3_range)
Output
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[1. 1.]
[1. 1.]]
[0 2 4 6 8]
NumPy Array Indexing
Knowing the basics of NumPy array indexing is important for analyzing and
manipulating the array object.
Basic Indexing: Basic indexing in NumPy allows you to access elements of an
array using indices.
Example:
import numpy as np
# Create a 1D array
arr1d = np.array([10, 20, 30, 40, 50])
# Negative indexing
print("Negative indexing:", arr1d[-1])
# Create a 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Output
Single element access: 30
Negative indexing: 50
Multidimensional array access: 4
Slicing: Just like lists in Python, NumPy arrays can be sliced. As arrays can be
multidimensional, you need to specify a slice for each dimension of the array.
Example:
import numpy as np
Output
Range of Elements: [[4 5 6]]
Multidimensional Slicing: [2 5]
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
Output
Elements at indices (0, 3), (1, 2), (2, 1),(3, 0):
[4. 6. 0. 3.]
[ Elements greater than 0:
[2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]
NumPy Basic Operations
Element-wise operations in NumPy allow you to perform mathematical operations
on each element of an array individually, without the need for explicit loops.
Example:
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
# Addition
add = x + y
print("Addition:",add)
# Subtraction
subtract = x - y
print("substration:",subtract)
# Multiplication
multiply = x * y
print("multiplication:",multiply)
# Division
divide = x / y
print("division:", divide)
Output
Addition: [5 7 9]
substration: [-3 -3 -3]
multiplication: [ 4 10 18]
division: [0.25 0.4 0.5 ]
Unary Operation: These operations are applied to each individual element in
the array, without the need for multiple arrays (as in binary operations).
Example:
import numpy as np
Output
Absolute value: [3 1 0 1 3]
Output
Array 1: [1 2 3]
Array 2: [4 5 6]
Addition Result: [5 7 9]
NumPy ufuncs
NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These
functions also operate elementwise on an array, producing an array as output.
Example:
import numpy as np
# exponential values
a = np.array([0, 1, 2, 3])
print ("Exponent of array elements:", np.exp(a))
Output:
Sine values of array elements: [ 0.00000000e+00 1.00000000e+00 1.22464680e-
16]
Exponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692]
Square root of array elements: [ 0. 1. 1.41421356 1.73205081]
NumPy Sorting Arrays
We can use a simple np.sort() method for sorting Python NumPy arrays.
Example:
import numpy as np
Output
Array sorted by names:
[(b'Aakash', 2009, 9.0 ) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5)
(b'Pankaj', 2008, 7.9)]
Trigonometric Functions
NumPy has standard trigonometric functions which return trigonometric ratios for a given angle
in radians.
numpy.sin(x[, out]) = ufunc ‘sin’) : This mathematical function helps user to calculate
trignmetric sine for all x(being the array elements).
Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]
Sine values :
[ 0.00000000e+00 1.00000000e+00 8.66025404e-01 1.22464680e-16]
numpy.cos(x[, out]) = ufunc ‘cos’) : This mathematical function helps user to calculate
trignmetric cosine for all x(being the array elements).
# Python program explaining
# cos() function
import numpy as np
import math
in_array = [0, math.pi / 2, np.pi / 3, np.pi]
print ("Input array : \n", in_array)
cos_Values = np.cos(in_array)
print ("\nCosine values : \n", cos_Values)
Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]
Cosine values :
[ 1.00000000e+00 6.12323400e-17 5.00000000e-01 -1.00000000e+00]
FUNCTION DESCRIPTION
Hyperbolic Functions –
numpy.sinh(x[, out]) = ufunc ‘sin’) : This mathematical function helps user to calculate
hyperbolic sine for all x(being the array elements).
import numpy as np
import math
in_array = [0, math.pi / 2, np.pi / 3, np.pi]
print ("Input array : \n", in_array)
Sinh_Values = np.sinh(in_array)
print ("\nSine Hyperbolic values : \n", Sinh_Values)
Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]
numpy.cosh(x[, out]) = ufunc ‘cos’) : This mathematical function helps user to calculate
hyperbolic cosine for all x(being the array elements).
Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]
FUNCTION DESCRIPTION
Output :
Input array :
[0.5, 1.5, 2.5, 3.5, 4.5, 10.1]
Rounded values :
[ 0. 2. 2. 4. 4. 10.]
Input array :
[0.53, 1.54, 0.71]
Rounded values :
[ 1. 2. 1.]
Input array :
[0.5538, 1.33354, 0.71445]
Rounded values :
[ 0.554 1.334 0.714]
numpy.round_(arr, decimals = 0, out = None) : This mathematical function round an array to
the given number of decimals.
Output :
Input array :
[0.5, 1.5, 2.5, 3.5, 4.5, 10.1]
Rounded values :
[ 0. 2. 2. 4. 4. 10.]
Input array :
[0.53, 1.54, 0.71]
Rounded values :
[ 1. 2. 1.]
Input array :
[0.5538, 1.33354, 0.71445]
Rounded values :
[ 0.554 1.334 0.714]
FUNCTION DESCRIPTION
numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype =
None) : This mathematical function helps user to calculate exponential of all the elements in the
input array.
Output :
Input array : [1, 3, 5]
Output array : [ 2.71828183 20.08553692 148.4131591 ]
numpy.log(x[, out] = ufunc ‘log1p’) : This mathematical function helps user to
calculate Natural logarithm of x where x belongs to all the input array elements.
Natural logarithm log is the inverse of the exp(), so that log(exp(x)) = x. The natural logarithm
is log in base e.
Output :
Input array : [1, 3, 5, 256]
Output array : [ 0. 1.09861229 1.60943791 5.54517744]
np.log(4**4) : 5.54517744448
np.log(2**8) : 5.54517744448
FUNCTION DESCRIPTION
Return the natural logarithm of one plus the input array, element-
log1p()
wise.
Note: For integer arguments with absolute value larger than 1, the result is always zero because
of the way Python handles integer division. For integer zero the result is an overflow.
Output :
Input number : 2.0
Output number : 0.5
numpy.divide(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’,
dtype = None) : Array element from first array is divided by elements from second element (all
happens element-wise). Both arr1 and arr2 must have same shape and element in arr2 must not
be zero; otherwise it will raise an error.
Output array :
[ 1. 9. 0.5 4.2 3.83333333]
FUNCTION DESCRIPTION
power() First array elements raised to powers from second array, element-wise.
floor_divide() Return the largest integer smaller or equal to the division of the inputs.
float_power() First array elements raised to powers from second array, element-wise.
FUNCTION DESCRIPTION
Output :
Is Real : [False True]
Output :
Output conjugated complex number of 2+4j : (2-4j)
Output conjugated complex number of 5-8j: (5+8j)
Special functions –
numpy.cbrt(arr, out = None, ufunc ‘cbrt’) : This mathematical function helps user to
calculate cube root of x for all x being the array elements.
Output :
Input array : [1, 2, 3, 4, 5, 6, 7, 8]
Output array : [2 2 3 4 5 6 6 6]
FUNCTION DESCRIPTION
real_if_close() If complex input returns a real array if complex parts are close to zero.
nan_to_num() Replace NaN with zero and infinity with large finite numbers.
This module can be used to perform random actions such as generating random numbers,
printing random a value for a list or string, etc. It is an in-built function in Python.
import random
a = [1, 2, 3, 4, 5, 6]
print(random.choice(a))
Output
3
Example 2: Using seed() for Reproducible Output
Random numbers depend on the seeding value. For example, if the seeding value is 5 then the
output of the below program will always be the same. Therefore, it must not be used for
encryption.
The code sets the random number generator's seed to 5 using random.seed(5). It then prints
two random floating-point numbers between 0 and 1 using random.random(). The seed makes
these numbers the same every time we run the code with a seed of 5.
import random
random.seed(5)
print(random.random())
print(random.random())
Output
0.6229016948897019
0.7417869892607294
import random
r1 = random.randint(5, 15)
print(r1)
r2 = random.randint(-10, -2)
print(r2)
Output
8
-7
Explanation:
r1 is a andom number between 5 and 15.
r2 is a random number between -10 and -2.
Example 4: Generate a Random Float Between 0 and 1
A random.random() method is used to generate random floats between 0.0 to 1.
Syntax: random.random()
Output
0.8443722499369146
Explanation: random() generates a float number in the range [0.0, 1.0).
import random
a = [1, 2, 3, 4, 5, 6]
print(random.choice(a))
s = "geeks"
print(random.choice(s))
tup = (1, 2, 3, 4, 5)
print(random.choice(tup))
Output
2
g
2
Explanation: choice() picks a random element from a list, string, or tuple.
a = [1, 2, 3, 4, 5]
print(sample(a,3))
b = (4, 5, 6, 7, 8)
print(sample(b,3))
c = "45678"
print(sample(c,3))
Output
[4, 2, 3]
[4, 7, 8]
['6', '4', '8']
Explanation: sample() returns a list of unique random elements from the input sequence.
import random
a = [1, 2, 3, 4, 5]
random.shuffle(a)
print("After shuffle : ")
print(a)
random.shuffle(a)
print("\nSecond shuffle : ")
print(a)
Output
After shuffle :
[1, 4, 2, 5, 3]
Second shuffle :
[1, 4, 3, 5, 2]
Explanation: shuffle() changes the order of elements in the list randomly, in-place.
Numpy - String Functions & Operations
NumPy String functions belong to the numpy.char module and are designed to perform
element-wise operations on arrays. These functions can help to handle and manipulate string
data efficiently.
In this article, we’ll explore the various string functions provided by NumPy along with their
examples.
String Operations
numpy.lower(): This function returns the lowercase string from the given string. It converts
all uppercase characters to lowercase. If no uppercase characters exist, it returns the original
string.
import numpy as np
# converting to lowercase
print(np.char.lower(['GEEKS', 'FOR']))
# converting to lowercase
print(np.char.lower('GEEKS'))
Output
['geeks' 'for']
geeks
numpy.split() : This function returns a list of strings after breaking the given string by the
specified separator.
import numpy as np
# splitting a string
print(np.char.split('geeks for geeks'))
# splitting a string
print(np.char.split('geeks, for, geeks', sep = ','))
Output
['geeks', 'for', 'geeks']
['geeks', ' for', ' geeks']
numpy.join() : This function is a string method and returns a string in which the elements of
sequence have been joined by str separator.
import numpy as np
# splitting a string
print(np.char.join('-', 'geeks'))
# splitting a string
print(np.char.join(['-', ':'], ['geeks', 'for']))
Output
g-e-e-k-s
['g-e-e-k-s' 'f:o:r']
FUNCTION DESCRIPTION
numpy.strip() It is used to remove all the leading and trailing spaces from a string.
It converts the first character of a string to capital (uppercase) letter. If the string has its
numpy.capitalize()
first character as capital, then it returns the original string.
numpy.center() It creates and returns a new string which is padded with the specified character..
It is used to convert from one encoding scheme, in which argument string is encoded to
numpy.decode()
the desired encoding scheme.
numpy.ljust() Return an array with the elements of a left-justified in a string of length width.
numpy.rjust() For each element in a, return a copy with the leading characters removed.
numpy.strip() For each element in a, return a copy with the leading and trailing characters removed.
numpy.rstrip() For each element in a, return a copy with the trailing characters removed.
For each element in a, return a list of the words in the string, using sep as the delimiter
numpy.rsplit()
string.
It is used to convert the first character in each word to Uppercase and remaining
numpy.title()
characters to Lowercase in string and returns new string.
Returns the uppercased string from the given string. It converts all lowercase characters
numpy.upper()
to uppercase.If no lowercase characters exist, it returns the original string.
String Information
numpy.count() : This function returns the number of occurrences of a substring in the given
string.
import numpy as np
# counting a substring
print(np.char.count(a,'geek'))
# counting a substring
print(np.char.count(a, 'fo'))
Output
[1 0 1]
[0 1 0]
numpy.rfind() : This function returns the highest index of the substring if found in given
string. If not found then it returns -1.
import numpy as np
# counting a substring
print(np.char.rfind(a,'geek'))
# counting a substring
print(np.char.rfind(a, 'fo'))
Output
[ 0 -1 0]
[-1 0 -1]
numpy.isnumeric() : This function returns “True” if all characters in the string are numeric
characters, Otherwise, It returns “False”.
import numpy as np
# counting a substring
print(np.char.isnumeric('geeks'))
# counting a substring
print(np.char.isnumeric('12geeks'))
Output
False
False
FUNCTION DESCRIPTION
It returns the lowest index of the substring if it is found in given string. If its is not
numpy.find()
found then it returns -1.
It returns “True” if all characters in the string are alphabets, Otherwise, It returns
numpy.isalpha()
“False”.
It returns true if all characters in a string are decimal. If all characters are not decimal
numpy.isdecimal()
then it returns false.
numpy.isdigit() It returns “True” if all characters in the string are digits, Otherwise, It returns “False”.
It returns “True” if all characters in the string are lowercase, Otherwise, It returns
numpy.islower()
“False”.
Returns true for each element if there are only whitespace characters in the string and
numpy.isspace()
there is at least one character, false otherwise.
Returns true for each element if the element is a titlecased string and there is at least
numpy.istitle()
one character, false otherwise.
Returns true for each element if all cased characters in the string are uppercase and
numpy.isupper()
there is at least one character, false otherwise.
Returns the highest index of the substring inside the string if substring is found.
numpy.rindex()
Otherwise it raises an exception.
numpy.startswith(
Returns True if a string starts with the given prefix otherwise returns False.
)
String Comparison
import numpy as np
print(a)
Output
False
import numpy as np
print(a)
Output
True
numpy.greater(): This function checks whether string1 is greater than string2 or not.
import numpy as np
print(a)
Output
True
FUNCTION DESCRIPTION