Python - Uneven Sized Matrix Column Product


In this article we will learn about various methods using which we can find products of uneven size matrix columns. Working with matrices is very common for fields like data analysis, machine learning, so there can be situations where we have to find the matrix column product which can be a challenging task.

Let’s see some examples for finding the uneven size matrix column product −

Method 1: Using a Simple Loop

In this method we will use the concept of simple nested loop and we will iterate through the matrix column and compute their products.

Example

def col_product_loop(mat):
   prod = []
   max_row_length = max(len(row) for row in mat)
   for col in range(max_row_length):
      col_product = 1
      for row in matrix:
         if col < len(row):
            col_product *= row[col]
         prod.append(col_product)
      return prod

   mat = [[1, 2, 3],
         [4, 5],
         [6, 7, 8, 9]]

products_col = col_product_loop(mat)
print("Product of column is :", products_col)

Output

Product of column is: [24, 70, 24, 9]

Explanation

Here in the above program we are taking care that we iterate over the large size row using max(len(row) for row in matrix. Inside the inner loop, we added an if condition to check if the current column index is within the row's range. If this condition is getting satisfied, then we multiply the index value. The products are then stored in a list and returned as the final result.

Method 2: Using NumPy

In this method we will use the concept of NumPy which provides us operations to work with arrays and matrix.

Example

import numpy as np

def col_product_numpy(mat):
   max_len = max(len(row) for row in mat)
   padded_matrix = [row + [1] * (max_len - len(row)) for row in mat]
   return np.product(padded_matrix, axis=0).tolist()

   mat = [[1, 2, 3],
         [4, 5],
         [6, 7, 8, 9]]

products_col = col_product_numpy(mat)
print("Product of column is:", products_col)

Output

Product of column is: [24, 70, 24, 9]

Explanation

Here in the above program we created a new matrix where all rows have the same length and we padded the shorter row with ones. Appending value as 1 will not affect the final result as multiplying the value with 1 will result as the same value. Then we calculate the product of the columns.

Method 3: Using List Comprehension

In this method we will use the concept of List comprehension which provides us an efficient way to create lists and calculate the column product.

Example

def column_product_comprehension(mat):
   max_rw = max(len(row) for row in mat)
   return [eval('*'.join(str(row[col]) for row in mat if col < len(row))) for col in range(max_rw)]

   mat = [[1, 2, 3],
         [4, 5],
         [6, 7, 8, 9]]

products_col = column_product_comprehension(mat)
print("Product of column is:", products_col)

Output

Product of column is: [24, 70, 24, 9]

Explanation

Here in the above program we are using the list comprehension method to iterate over the columns using range(max_rw). Here max_rw is the maximum length of any row. Then we join each element within the column for each row which is in the representation of the string. Then we use the eval() method to calculate the product.

Method 4: Using numpy.prod() and np.apply_along_axis()

In this method we will use the numpy.prod() and np.apply_along_axis() method to find the product of columns.

Example

import numpy as np

def column_product_np_apply(mat):
   max_len = max(len(column) for column in mat)
   padded_matrix = [column + [1] * (max_len - len(column)) for column in mat]
   return np.apply_along_axis(np.prod, axis=0, arr=padded_matrix).tolist()


   mat = [[1, 2, 3],
         [4, 5],
         [6, 7, 8, 9]]

products_col = column_product_np_apply(mat)
print("Product of column is:", products_col)

Output

Product of column is: [24, 70, 24, 9]

Explanation

Here in the above program we are using the numpy.prod() and np.apply_along_axis() method to get the product of the column. We padded the shorter row with ones. Appending value as 1 will not affect the final result as multiplying the value with 1 will result as the same value. Then we apply the np.apply_along_axis with the np.prod method as the function and we added axis=0 for applying the product function along each column.

Method 5: Using Pandas Dataframe

In this method we will use the concept of pandas dataframe library which is very popular for data manipulation. We will use the dataframe object provided by the pandas dataframe which can handle the uneven size matrix.

Example

import pandas as pd

def column_product_pandas(mat):
   df = pd.DataFrame(mat)
   return df.product(axis=0).tolist()


   mat = [[1, 2, 3],
         [4, 5],
         [6, 7, 8, 9]]

products_col = column_product_pandas(mat)
print("Product of column is:", products_col)

Output

Product of column is: [24.0, 70.0, 24.0, 9.0]

Explanation

Here in the above program we converted the matrix into the pandas dataframe using pd.DataFrame() and we used the product()function with axis=0 to compute the product of the columns element.

Method 6: Using Recursive Function

In this method we will use the concept of recursion function to calculate the columns product.

Example

def column_product_recursive(mat, row_i=0, col_i=0, prod=[]):
   if row_i == len(mat):
      return prod

   if col_i == len(mat[row_i]):
      return column_product_recursive(mat, row_i + 1, 0, prod)

   current_element = mat[row_i][col_i]
   if col_i >= len(prod):
      prod.append(current_element)
   else:
      prod[col_i] *= current_element

   return column_product_recursive(mat, row_i, col_i + 1, prod)

   mat = [[1, 2, 3],
         [4, 5],
         [6, 7, 8, 9]]

products_col = column_product_recursive(mat)
print("Product of column is:", products_col)

Output

Product of column is: [24, 70, 24, 9]

Explanation

In the above program we called a recursion function and passed the matrix along with row index and column index which is used to keep track of the current row and column which is being processed. We used the base case when the length of row will reach the length of the matrix which denotes that all the rows have been processed. So, in this case we return the product list. We take out the element from the current list and multiply with the element present in the product list. In case the index of the column becomes greater than the length of the product list then we append the new list. Then we called the recursion function by increasing the next column to process the next column element.

Conclusion

So, we get to know about various methods using which we can calculate the product of the column element of any uneven size matrix. We saw different methods like looping, list comprehension, recursive, numpy to perform this operation. You can choose any of the above methods which is suitable for you.

Updated on: 06-Oct-2023

37 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements