Numpy – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Thu, 13 Apr 2023 06:58:33 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Numpy – Shishir Kant Singh https://shishirkant.com 32 32 187312365 NumPy fromiter() function https://shishirkant.com/numpy-fromiter-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-fromiter-function Thu, 13 Apr 2023 06:58:28 +0000 https://shishirkant.com/?p=3265 The numpy.fromiter() function is used to create an ndarray by using a python iterable object. This method mainly returns a one-dimensional ndarray object.

Syntax of numpy.fromiter():

Below we have the required syntax to use this function:

numpy.fromiter(iterable, dtype, count)  

Parameters:

Let us discuss the parameters of the above function:

  1. iterable
    This parameter is used to represents an iterable object.
  2. dtype
    This parameter is used to represent the data type of the resultant array items.
  3. count:
    This parameter is used to represent the number of items to read from the buffer in the array.

Note: It is important to specify a count parameter in order to improve performance of this function. Because the count parameter allows the fromiter() function to pre-allocate the output array rather than resizing it on demand.

Returned Value:

This function will return the array created using the iterable object.

Let us now discuss some examples using fromiter() function.

Basic Example:

Below we have the code snippet of the example using this function:

import numpy as np  

a = [0,2,4,9,10,8]  
it = iter(a)  
x = np.fromiter(it, dtype = float)  

print("The output array is :")
print(x)  

print("The type of output array is:")
print(type(x))  

Output:


The output array is :
[ 0. 2. 4. 9. 10. 8.]
The type of output array is:
<class 'numpy.ndarray'>
]]>
3265
NumPy linspace() function https://shishirkant.com/numpy-linspace-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-linspace-function Thu, 13 Apr 2023 06:57:10 +0000 https://shishirkant.com/?p=3262 This function is used to return evenly spaced numbers over a specified interval.

  • This function is similar to Numpy arange() function with the only difference being, instead of step size, the number of evenly spaced values between the interval is specified using the num argument.
  • With the help of this function, the step size is calculated implicitly.
  • In this function, the endpoint of the interval can optionally be excluded.
  • In the newest versions of NumPy, the non-scalar values of start and stop parameters(used to define the interval) are supported by this function.

Syntax of numpy.linspace():

The required syntax to use this function is as follows:

numpy.linspace(start, stop, num, endpoint, retstep, dtype)   

Parameters:

The parameters of the above-mentioned function are as follows:

  • start
    This parameter is used to represents the starting value of the interval.
  • stop
    This parameter is used to represents the stopping value of the interval.
  • num
    This parameter indicates the amount of evenly spaced samples over the interval to be generated. The default value of this parameter is 50.
  • endpoint
    This parameter’s true value is used to indicate that the stopping value is included in the interval.
  • retstep
    The value of this parameter is a boolean value and it is used to represent the steps and samples between the consecutive numbers.
  • dtype
    This parameter is used to represent the data type of the array items.

Returned Values:

This function will return the array within the range specified.

This function will return the value of step in the case if retstep parameter is True which usually indicates the size of the spacing between the samples.

Now it’s time to take a look at the examples using this function.

Example 1:

Below we have the code snippet explaining how to use this function:

import numpy as np  

a = np.linspace(20, 40, 8, endpoint = True)  
print("The array over the given range is ")
print(a) 

Output:


The array over the given range is
[20. 22.85714286 25.71428571 28.57142857 31.42857143 34.28571429
37.14285714 40. ]

Example 2:

Below we have the code snippet for the graphical illustration of this function, using Matplotlib library:

import matplotlib.pyplot as plt

N = 10
y = np.zeros(N)
x1 = np.linspace(0, 20, N, endpoint=True)
x2 = np.linspace(0, 20, N, endpoint=False)
plt.plot(x1, y, '*')
plt.plot(x2, y + 0.8, 'o')
plt.show()

Output:

Numpy linspace() code example
Numpy linspace() code example
]]>
3262
NumPy logspace() function https://shishirkant.com/numpy-logspace-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-logspace-function Thu, 13 Apr 2023 06:55:25 +0000 https://shishirkant.com/?p=3259 The numpy.logspace() function in Numpy is used to create an array by using the numbers that are evenly separated on a log scale.

Syntax of numpy.logspace():

The syntax to use this function is as follows:

numpy.logspace(start, stop, num, endpoint, base, dtype)  

Parameters:

The parameters of this function are as follows:

  • start
    This parameter is used to represent the starting value of the interval in the base.
  • stop
    This parameter is used to represent the stopping value of the interval in the base.
  • num
    This parameter is used to indicate the number of values between the range.
  • endpoint
    This parameter’s value is in boolean and it is used to make the value represented by stop as the last value of the interval.
  • base
    This parameter is used to represent the base of the log space.
  • dtype
    This parameter is used to represent the data type of the array items.

Returned Values:

This function will return the array in the specified range.

Now it’s time to look at a few examples in order to gain an understanding of this function.

Example 1:

Below we have the code snippet where we will use this function:

import numpy as np  

arr = np.logspace(20, 30, num = 7,base = 4, endpoint = True)  
print("The array over the given range is ")
print(arr)

Output:


The array over the given range is
[1.09951163e+12 1.10823828e+13 1.11703419e+14 1.12589991e+15
1.13483599e+16 1.14384301e+17 1.15292150e+18]

Example 2:

In the example given below we will cover the graphical representation of numpy.logspace() function using matplotlib:

import numpy as np
import matplotlib.pyplot as plt

N = 20
x1 = np.logspace(0.1, 1, N, endpoint=True)
x2 = np.logspace(0.1, 1, N, endpoint=False)
y = np.zeros(N)

plt.plot(x1, y, 'o')
plt.plot(x2, y + 0.8, 'o')
plt.ylim([-0.5, 1])
plt.show()

Output of the following code:

Numpy logspace() code example
]]>
3259
NumPy frombuffer() function https://shishirkant.com/numpy-frombuffer-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-frombuffer-function Thu, 13 Apr 2023 06:53:48 +0000 https://shishirkant.com/?p=3256 The numpy.frombuffer() function of the Numpy library is used to create an array by using the specified buffer.

This function interprets a buffer as a 1-dimensional array.

Syntax of frombuffer():

Given below is the required syntax that is used for numpy.frombuffer() function:

numpy.frombuffer(buffer, dtype, count, offset) 

Parameters:

Let us discuss the parameters of the above constructor:

  • buffer
    This parameter is used to represent an object that exposes a buffer interface.
  • dtype
    This parameter is used to represent the data type of the returned data type array. The default value of this parameter is 0.
  • count
    This parameter represents the length of the returned ndarray. The default value of this parameter is -1.
  • offset
    This parameter indicates the starting position to read from. The default value of this parameter is 0.

Let us now discuss some examples using frombuffer() function.

Basic Example:

Below we have the code snippet in order to understand the working of this function:

import numpy as np  

input = b'Welcome to ShishirKant!!!It is a best place for you to learn coding online..'  
print("The type of input is:") 
print(type(input))

a = np.frombuffer(input, dtype = "S1")  
print("The Output is:") 
print(a)

print("Type of Output is:")
print(type(a))  

Output:

The type of input is:
<class 'bytes'>
The Output is:
[b'W' b'e' b'l' b'c' b'o' b'm' b'e' b' ' b't' b'o' b' ' b'S' b'h' b'i'
b's' b'h' b'i' b'r' b'K' b'a' b'g' b'n' b't' b'!' b'!' b'!' b'I' b't'
b' ' b'i' b's' b' ' b'a' b' ' b'b' b'e' b's' b't' b' ' b'p' b'l' b'a'
b'c' b'e' b' ' b'f' b'o' b'r' b' ' b'y' b'o' b'u' b' ' b't' b'o' b' '
b'l' b'e' b'a' b'r' b'n' b' ' b'c' b'o' b'd' b'i' b'n' b'g' b' ' b'o'
b'n' b'l' b'i' b'n' b'e' b'.' b'.']
Type of Output is:
<class 'numpy.ndarray'>
]]>
3256
NumPy asarray() function https://shishirkant.com/numpy-asarray-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-asarray-function Thu, 13 Apr 2023 06:50:25 +0000 https://shishirkant.com/?p=3253 The numpy.asarray() function in Numpy is used to convert the input or any existing data into an array.

  • The existing data can be in the form of Lists, Tuples, tuples of tuples, list of tuples, tuples of lists, etc.
  • In case if you want to convert any python sequence into the Numpy array object i.e ndarray then this function is helpful for you.

Syntax of numpy.asarray():

Given below is the basic syntax to use this function:

numpy.asarray(sequence,  dtype, order)  

Parameters:

Let us discuss the parameters mentioned above for the asarray() function:

  • sequence
    This parameter is used to indicate the input data that can be in any form and is to be converted into an array. This parameter includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
  • dtype
    This parameter is used to indicate the data type of each item of the array. It is an optional parameter with default value None.
  • order
    This parameter is used to indicate the memory representation that is whether to use row-major (C-style) or column-major (Fortran-style) The default value is set to ‘C’.

Returned Values:

This function will return an array with all the values from the sequence used to create the array. If the input is already an ndarray with matching dtype and order then this function will not create any copy.

Now it’s time to take a look at some examples of this function.

Example 1:

In the code snippet given below we will convert a Python list into an array:

import numpy as np

mylist = [1, 2,4,5,8,10]
np.asarray(mylist)

Output:


array([ 1, 2, 4, 5, 8, 10])

Example 2:

In the code snippet below we will create a NumPy array from a Python tuple:

import numpy as np  

inp = (10,9,1,2,3,4,5,6,7,8)     
a = np.asarray(inp); 
print("The output is:")
print(a)  
print("The datatype of output is:")
print(type(a))  

Output:


The output is:
[10 9 1 2 3 4 5 6 7 8]
The datatype of output is:
<class 'numpy.ndarray'>

Example 3:

In the code snippet given below we will create an array using more than one list:

import numpy as np  

l = [[1,2,3,4,5,6,7],[8,9],[12,34,45]]  
a = np.asarray(l);
print("The data type of output is:")
print(type(a))  
print("The output array is:")
print(a)  

Output:


The data type of output is:
<class 'numpy.ndarray'>
The output array is:
[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9]) list([12, 34, 45])]
]]>
3253
NumPy dot() function https://shishirkant.com/numpy-dot-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-dot-function Thu, 13 Apr 2023 06:48:03 +0000 https://shishirkant.com/?p=3250 The dot() function is mainly used to calculate the dot product of two vectors.

  • This function can handle 2D arrays but it will consider them as matrix and will then perform matrix multiplication.
  • In the case, if an array a is an N-D array and array b is an M-D array (where, M >= 2) then it is a sum product over the last axis of a and the second-to-last axis of b:
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

Syntax of numpy.dot():

The syntax required to use this function is as follows:

numpy.dot(a, b, out=None)

Parameters:

Let us discuss the parameters of this function:

  • a
    This is the first parameter. If “a” is complex number then its complex conjugate is used for the calculation of the dot product.
  • b
    This is the second parameter. If “b” is complex then its complex conjugate is used for the calculation of the dot product.
  • out
    This indicates the output argument. This out must have the exact kind that would be returned if it was not used. Otherwise it must be C-contiguous and its dtype must be the dtype that would be returned for dot(a, b).

Returned Values:

The dot() function will return the dot product of a and b. If both a and b are scalars or if both are 1-D arrays then a scalar value is returned, otherwise an array is returned. If out is given, then it is returned.

Note: The ValueError is raised in the case if the last dimension of a is not the same size as the second-to-last dimension of b.

Example 1:

The code snippet is as follows where we will use dot() function:

import numpy as np

#Let us take scalars first 
a = np.dot(8, 4) 
print("The dot Product of above given scalar values : ")
print(a) 

# Now we will take 1-D arrays 
vect_a = 4 + 3j
vect_b = 8 + 5j

dot_product = np.dot(vect_a, vect_b) 
print("The Dot Product of two 1-D arrays is : ")
print(dot_product) 

Output:


The dot Product of above given scalar values :
32
The Dot Product of two 1-D arrays is :
(17+44j)

Explanation of the calculation of dot product of two 1D Arrays:

vect_a = 4+ 3j
vect_b = 8 + 5j

Now calculating the dot product:
= 4(8 + 5j) + 3j(8 – 5j)
= 32+ 20j + 24j – 15
= 17 + 44j

Example 2:

Now let’s create two numpy arrays and then find the dot product for them using the dot() function:

import numpy as np

a = np.array([[50,100],[12,13]])  
print("The Matrix a is:")
print (a)

b = np.array([[10,20],[12,21]])  
print("The Matrix b is :")
print(b)

dot = np.dot(a,b)  
print("The dot product of a and b is :")
print(dot)

Output:

Numpy dot() function example
]]>
3250
Numpy bitwise_and() function https://shishirkant.com/numpy-bitwise_and-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-bitwise_and-function Thu, 13 Apr 2023 06:45:58 +0000 https://shishirkant.com/?p=3247 In Numpy, the bitwise_and() function is mainly used to perform the bitwise_and operation.

  • This function will calculate the bit-wise AND of two arrays, element-wise.
  • The bitwise_and() function calculates the bit-wise AND of the underlying binary representation of the integers in the input array.

Let us take a look at the truth table of AND operation:

If and only if both the bits are 1 only then the output of the AND result of the two bits is 1 otherwise it will be 0.

Syntax of bitwise_and():

The syntax required to use this function is as follows:

numpy.bitwise_and(x1, x2, /, out, *, where=True, casting='same_kind', order='K', dtype,subok=True[, signature, extobj]) = <ufunc 'bitwise_and'>

Parameters:

Let us now take a look at the parameters of this function:

  • x1, x2
    These two are input arrays and with this function only integer and boolean types are handled. If x1.shape != x2.shape, then they must be broadcastable to a common shape (and this shape will become the shape of the output).
  • out
    This parameter mainly indicates a location in which the result is stored. If this parameter is provided, it must have a shape that the inputs broadcast to. If this parameter is either not provided or it is None then a freshly-allocated array is returned.
  • where
    This parameter is used to indicate a condition that is broadcast over the input. At those locations where the condition is True, the out array will be set to the b result, else the out array will retain its original value.

Returned Values:

This function will return a scalar if both x1 and x2 are scalars.

Example 1:

In the example below, we will illustrate the usage of bitwise_and() function:

import numpy as np

num1 = 15
num2 = 20
 
print ("The Input  number1 is :", num1)
print ("The Input  number2 is :", num2) 
   
output = np.bitwise_and(num1, num2) 
print ("The bitwise_and of 15 and 20 is: ", output) 

Output:


The input number1 is: 15
The input number2 is: 20
The bitwise_and of 15 and 20 is: 4

Example 2:

In the example below, we will apply the bitwise_and() function on two arrays:

import numpy as np
 
ar1 = [2, 8, 135]
ar2 = [3, 5, 115]
  
print ("The Input array1 is : ", ar1) 
print ("The Input array2 is : ", ar2)
   
output_arr = np.bitwise_and(ar1, ar2) 
print ("The Output array after bitwise_and: ", output_arr)

Output:


The Input array1 is : [2, 8, 135]
The Input array2 is : [3, 5, 115]
The Output array after bitwise_and: [2 0 3]
]]>
3247
NumPy bitwise_or() function https://shishirkant.com/numpy-bitwise_or-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-bitwise_or-function Thu, 13 Apr 2023 06:44:22 +0000 https://shishirkant.com/?p=3244 In Numpy, the bitwise_or() function is mainly used to perform the bitwise_or operation.

  • This function will calculate the bit-wise OR of two arrays, element-wise.
  • The bitwise_or() function calculates the bit-wise OR of the underlying binary representation of the integers in the input array.
  • It is important to note that if one of the corresponding bit in the operands is 1 then the resultant bit in the output of the OR operation will be set to 1, otherwise it will be set to 0.

Given below is the truth table of OR operation where you will see the OR result of the two bits is 1 if one of the bits is 1 otherwise the result will be 0.

Numpy bitwise_or function

Syntax of bitwise_or():

The syntax required to use this function is as follows:

numpy.bitwise_or(x1, x2, /, out, *, where=True, casting='same_kind', order='K', dtype, subok=True[, signature, extobj]) = <ufunc 'bitwise_or'>

Parameters:

let us now take a look at the parameters of this function:

  • x1, x2
    These two are input arrays and with this function, only integer and boolean types are handled. If x1.shape != x2.shape, then they must be broadcastable to a common shape (and this shape will become the shape of the output).
  • out
    This parameter mainly indicates a location in which the result is stored. If this parameter is provided, it must have a shape that the inputs broadcast to. If this parameter is either not provided or it is None then a freshly-allocated array is returned.
  • where
    This parameter is used to indicate a condition that is broadcast over the input. At those locations where the condition is True, the out array will be set to the ufunc result, else the out array will retain its original value.

Returned Values:

This function will return a scalar if both x1 and x2 are scalars.

Example 1:

In the example below, we will illustrate the usage of the bitwise_or() function:

import numpy as np

num1 = 15
num2 = 20
 
print ("The Input  number1 is: ", num1)
print ("The Input  number2 is: ", num2) 
   
output = np.bitwise_or(num1, num2) 
print ("The bitwise_or of 15 and 20 is: ", output) 

Output:


The input number1 is: 15
The input number2 is: 20
The bitwise_or of 15 and 20 is: 31

Example 2:

In the example below, we will use the bitwise_or() function with two arrays:

import numpy as np
 
ar1 = [2, 8, 135]
ar2 = [3, 5, 115]
  
print ("The Input array1 is : ", ar1) 
print ("The Input array2 is : ", ar2)
   
output_arr = np.bitwise_or(ar1, ar2) 
print ("The Output array after bitwise_or:", output_arr)

Output:


The Input array1 is : [2, 8, 135]
The Input array2 is : [3, 5, 115]
The Output array after bitwise_or: [ 3 13 247]

]]>
3244
NumPy invert() function https://shishirkant.com/numpy-invert-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-invert-function Thu, 13 Apr 2023 06:42:20 +0000 https://shishirkant.com/?p=3241
  • In case if any signed integer is passed to this function than the 2’s complement of the signed integer will be returned.
  • Syntax of numpy.invert():

    The syntax required to use this function is as follows:

    numpy.invert(x, /, out, *, where=True, casting='same_kind', order='K', dtype, subok=True[, signature, extobj]) = <ufunc 'invert'>

    Parameters:

    Let us now take a look at the parameters of this function:

    • x
      This parameter indicates an input array and with this function, only integer and boolean types are handled.
    • out
      This parameter mainly indicates a location in which the result is stored. If this parameter is provided, it must have a shape that the inputs broadcast to. If this parameter is either not provided or it is None then a freshly-allocated array is returned.
    • where
      This parameter is used to indicate a condition that is broadcast over the input. At those locations where the condition is True, the out array will be set to the ufunc result. Else the out array will retain its original value.

    Returned Values:

    This function will return a scalar if x is scalar.

    Example 1:

    In the example below, we will illustrate the usage of the invert() function:

    import numpy as np
    
    inp_num = 12
    print ("The Input number is: ", inp_num)
       
    outp_num = np.invert(inp_num) 
    print ("The inversion of 12 is: ", outp_num)

    Output:


    The Input number is: 12
    The inversion of 12 is: -13

    Example 2:

    In this example, we will use the invert() function with an array of integers:

    import numpy as np
     
    inp_arr = [1, 10, 15]
    print ("The Input array is: ", inp_arr)
       
    out_arr = np.invert(inp_arr) 
    print ("The Output array after inversion: ", out_arr) 

    Output:



    The Input array is: [1, 10, 15]
    The Output array after inversion: [ -2 -11 -16]
    ]]>
    3241
    NumPy bitwise_xor() function https://shishirkant.com/numpy-bitwise_xor-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-bitwise_xor-function Thu, 13 Apr 2023 06:40:40 +0000 https://shishirkant.com/?p=3238 In Numpy, the bitwise_xor() function is mainly used to perform the bitwise XOR operation.

    • This function will calculate the bitwise XOR of two arrays element-wise.
    • The bitwise_xor() function calculates the bitwise XOR of the underlying binary representation of the integers in the input array.
    • For the XOR operation, the bitwise_XOR() function implements the ^ (C/Python operator).

    Syntax of numpy.bitwise_xor():

    The syntax required to use this function is as follows:

    numpy.bitwise_xor(x1, x2, /, out, *, where=True, casting='same_kind', order='K', dtype, subok=True[, signature, extobj]) = <ufunc 'bitwise_xor'>

    Parameters:

    let us now take a look at the parameters of this function:

    • x1, x2
      These two are input arrays and with this function, only integer and boolean types are handled. If x1.shape != x2.shape, then they must be broadcastable to a common shape (and this shape will become the shape of the output).
    • out
      This parameter mainly indicates a location in which the result is stored. If this parameter is provided, it must have a shape that the inputs broadcast to. If this parameter is either not provided or it is None then a freshly-allocated array is returned.
    • where
      This parameter is used to indicate a condition that is broadcast over the input. At those locations where the condition is True, the out array will be set to the ufunc result, else the out array will retain its original value.

    Returned Values:

    This function will return a scalar if both x1 and x2 are scalars.

    Example 1:

    In the example below, we will illustrate the usage of bitwise_xor() function:

    import numpy as np
    
    num1 = 15
    num2= 20
     
    print ("The Input  number1 is :", num1)
    print ("The Input  number2 is :", num2) 
       
    output = np.bitwise_xor(num1, num2) 
    print ("The bitwise_xor of 15 and 20 is: ", output) 

    Output:


    The Input number1 is: 15
    The Input number2 is: 20
    The bitwise_xor of 15 and 20 is: 27

    Example 2:

    In this example, we will use two arrays and then apply the bitwise_xor() function to them:

    import numpy as np
     
    ar1 = [2, 8, 135]
    ar2 = [3, 5, 115]
      
    print ("The Input array1 is : ", ar1) 
    print ("The Input array2 is : ", ar2)
       
    output_arr = np.bitwise_xor(ar1, ar2) 
    print ("The Output array after bitwise_xor: ", output_arr)

    Output:


    The Input array1 is : [2, 8, 135]
    The Input array2 is : [3, 5, 115]
    The Output array after bitwise_xor: [ 1 13 244]
    ]]>
    3238