Open In App

Python – Similar index elements Matrix

Sometimes, while working with data, we can have a problem in which we need to perform the construction of matrix from lists element vertically than horizontally. This kind of application can come in Data Science domains in which we need to construct Matrix from several lists. Lets discuss certain ways in which this task can be performed.

Method #1: Using zip() + map()The combination of above functions can be used to perform this task. In this, we pair up lists using zip() and then using map() the construction of matrix occurs from the paired up lists.






# Python3 code to demonstrate
# Similar index elements Matrix
# using zip() + map()
 
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
 
# Similar index elements Matrix
# using zip() + map()
res = []
res += map(list, zip(test_list1, test_list2, test_list3))
     
# printing result
print ("The matrix after cummulation is : " + str(res))

Output
The original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cummulation is : [[3, 1, 7], [4, 2, 9], [5, 6, 8]]

Method #2: Using list comprehension + zip()This is yet another way in which this task can be performed. In this, we perform the task of map() in above with the help of list comprehension.






# Python3 code to demonstrate
# Similar index elements Matrix
# using zip() + list comprehension
 
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
 
# Similar index elements Matrix
# using zip() + list comprehension
res = [list(sub) for sub in zip(test_list1, test_list2, test_list3)]
     
# printing result
print ("The matrix after cummulation is : " + str(res))

Output
The original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cummulation is : [[3, 1, 7], [4, 2, 9], [5, 6, 8]]

Method #3: Using numpy




# Python3 code to demonstrate
# Similar index elements Matrix
# using numpy library
import numpy as np
 
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
 
# Similar index elements Matrix
# using numpy library
res = np.column_stack((test_list1, test_list2, test_list3))
 
# printing result
print("The matrix after cumulation is : \n" + str(res))
#This code is contributed by Edula Vinay Kumar Reddy

Output:

The original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cumulation is : 
[[3 1 7]
[4 2 9]
[5 6 8]]

Time complexity: O(n)
Auxiliary Space: O(n)

Explanation: In this approach, we use the numpy library which provides us the column_stack function. This function takes a tuple of 1D arrays as input and returns a 2D array. The input arrays are stacked as columns in the output array, which results in the formation of a matrix with similar index elements.

Method 4: Using a simple for loop




# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
 
# Using for loop
res = []
for i in range(len(test_list1)):
    row = []
    row.append(test_list1[i])
    row.append(test_list2[i])
    row.append(test_list3[i])
    res.append(row)
 
# printing result
print("The matrix after cumulation is : ")
for row in res:
    print(row)

Output
The original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cumulation is : 
[3, 1, 7]
[4, 2, 9]
[5, 6, 8]

Time complexity: O(n^2), where n is the length of each list. Since we are iterating over each element of the list and appending it to a new list, the time complexity will be O(n^2).
Auxiliary space: O(n^2), since we are creating a new list to store the matrix.

Method 5: Using pandas DataFrame

The pandas library can be used to create a DataFrame from the input lists and then transpose the DataFrame to obtain the desired matrix.

Step-by-step approach:

  1. Importing the pandas library using the “import” statement and assigning an alias “pd”.
  2. Initializing three lists named “test_list1”, “test_list2”, and “test_list3” containing some integer values.
  3. Creating a DataFrame object by passing a dictionary of lists containing the input lists as values, and using column names as keys.
  4. Transposing the DataFrame to obtain the desired matrix. Transposing the DataFrame converts rows to columns and vice versa.
  5. Converting the transposed DataFrame to a nested list using the “.values.tolist()” method of the DataFrame object.
  6. Printing the result using the “print()” statement, along with a message.
  7. Using a “for” loop to iterate through each row of the resulting nested list, and printing each row using the “print()” statement.

Below is the implementation of the above approach:




import pandas as pd
 
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
 
# Creating a DataFrame from the input lists
df = pd.DataFrame({'list1': test_list1, 'list2': test_list2, 'list3': test_list3})
 
# Transposing the DataFrame to obtain the desired matrix
res = df.values.tolist()
 
# Printing the result
print("The matrix after cumulation is : ")
for row in res:
    print(row)

Output:

The matrix after cumulation is : 
[3, 1, 7]
[4, 2, 9]
[5, 6, 8]

Time complexity: O(n), where n is the length of the input lists.
Auxiliary space: O(n), for creating the DataFrame.

Method 6: Using  itertools:

Algorithm:

  1. Create an empty matrix (2D list) with dimensions equal to the number of columns of the input matrix and the number of rows equal to the length of any row of the input matrix.
  2. Iterate over the input matrix and insert the elements into the empty matrix at the appropriate positions.
  3. Return the transposed matrix.




import itertools
 
# Initializing lists
test_list1 = [3, 4, 5]
test_list2 = [1, 2, 6]
test_list3 = [7, 9, 8]
 
# Creating the matrix using itertools.zip_longest()
matrix = list(itertools.zip_longest(test_list1, test_list2, test_list3))
 
# Printing the original lists and the resulting matrix
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
print("The matrix after cumulation is : ")
for row in matrix:
    print(row)
#This code is contributed by Jyothi pinjala.

Output
The original list 1 is : [3, 4, 5]
The original list 2 is : [1, 2, 6]
The original list 3 is : [7, 9, 8]
The matrix after cumulation is : 
(3, 1, 7)
(4, 2, 9)
(5, 6, 8)

Time complexity:
Let’s assume the input matrix has m rows and n columns. The first step of creating the empty matrix takes O(nm) time. The second step of iterating over the input matrix and inserting elements into the empty matrix takes O(mn) time. Finally, transposing the matrix takes O(nm) time. Therefore, the overall time complexity is O(mn).

Space complexity:
The space complexity of this algorithm is also O(mn), as we need to create an empty matrix of size mxn to store the transposed matrix.


Article Tags :