Array operations in NumPy – Aggregate and Advanced Operations:

               Arrays in numpy has variety of operations like element-wise arithmetic, Scalar Operations, Aggregate and advanced functions. The basic operations are already discussed. Now,we discuss about the aggregate and advanced functions.

Python Numpy Code for Aggregate and Advanced Operations:

              This code starts from importing Numpy library. First,create two arrays with elements. Next,Aggregate functions like sum of all elements,Mean value,max and min values are calculated with built-in functions.

Advanced functions like Dot product,square root and exponential are also calculated with built-in function.

Code:

 import numpy as np

# Let us Create two arrays

s_arr1 = np.array([1, 3, 5, 7])

s_arr2 = np.array([2, 4, 6, 8])

#Aggregate functions

print("Sum:", np.sum(s_arr1))                  

print("Mean:", np.mean(s_arr1))                

print("Max:", np.max(s_arr2))                  

print("Min:", np.min(s_arr2))                  

# Advanced operations

print("Dot product:", np.dot(s_arr1, s_arr2))    

print("Square root:", np.sqrt(s_arr1))         

print("Exponential:", np.exp(s_arr2))          

Output:

Sum: 16

Mean: 4.0

Max: 8

Min: 2

Dot product: 100

Square root: [1.         1.73205081 2.23606798 2.64575131]

Exponential: [   7.3890561    54.59815003  403.42879349 2980.95798704]

Broadcasting arrays:

              This method is used to add 1D array with 2D arrays. Here, is the sample code.

Code:

import numpy as np1

#2D array (matrix) creation

A = np1.array([[1, 2, 1],

              [4, 5, 3]])

#1D array (vector) creation

b = np1.array([11, 20, 15])

# Broadcasting addition

C_add = np1.add(A, b)

print("Broadcasted Addition:\n", C_add)

# Broadcasting multiplication

C_mul = np1.multiply(A, b)

print("Broadcasted Multiplication:\n", C_mul)

Output:

Broadcasted Addition:

 [[12 22 16]

 [15 25 18]]

Broadcasted Multiplication:

 [[ 11  40  15]

 [ 44 100  45]]

These are the ways to implement advanced functions and aggregate functions in Python using Numpy. Hope, you understood the concept. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Datatypes and Variables in java script