Aggregations on matrix in Python
Aggregations are the data transformation techniques which produces scalar values from arrays. Let us implement this two ways
- 1. Using python code
- 2. Using Numpy
The code is given below…
1.Using python code:
This
method creates a matrix.It calculates the row wise sum,column wise sum and
overall sum. It also finds the maximum value in row wise and column wise.
Finally,it displays the values.
Code:
s_matrix = [
[2, 2, 1],
[6, 5, 4],
[3, 8, 9]
]
# Let us find Row-wise sum
row_sums = [sum(row) for row in s_matrix]
# Let us find Column-wise sum
col_sums = [sum(s_matrix[r][c] for r in
range(len(s_matrix))) for c in range(len(s_matrix[0]))]
# Sum of all the elements
total_sum = sum(sum(row) for row in s_matrix)
# To find maximum value in Row-wise
row_max = [max(row) for row in s_matrix]
# To find maximum value in Column-wise
col_max = [max(s_matrix[r][c] for r in range(len(s_matrix)))
for c in range(len(s_matrix[0]))]
print("Row elements sums:", row_sums)
print("Column elements sums:", col_sums)
print("Overall elements sum:", total_sum)
print("Row max Value:", row_max)
print("Column max Value:", col_max)
Output:
Row elements sums: [5, 15, 20]
Column elements sums: [11, 15, 14]
Overall elements sum: 40
Row max Value: [2, 6, 9]
Column max Value: [6, 8, 9]
This is the first method. Second method is given below.
2. Using numpy
This
method uses the built-in numpy package.
import numpy as np1
# Create a NumPy sample matrix
s_matrix = np1.array([
[3, 2, 1],
[9, 5, 4],
[6, 8, 7]
])
# let us perform Aggregations
row_sums = np1.sum(s_matrix, axis=1)
col_sums = np1.sum(s_matrix, axis=0)
total_sum = np1.sum(s_matrix)
row_max = np1.max(s_matrix, axis=1)
col_max = np1.max(s_matrix, axis=0)
print("Sum of Row elements:", row_sums)
print("Sum of Column elements:", col_sums)
print("Sum of Total elements:", total_sum)
print("Maximum value in the Row:", row_max)
print("Maximum value in the Column:", col_max)
Output:
Sum of Row elements: [ 6 18 21]
Sum of Column elements: [18 15 12]
Sum of Total elements: 45
Maximum value in the Row: [3 9 8]
Maximum value in the Column: [9 8 7]
This method is suitable for large matrices.
These are the methods to implement Aggregations on matrix in
python. Hope, this code is useful to you. Keep coding!!!
Comments
Post a Comment