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
test_list1 = [ 3 , 4 , 5 ]
test_list2 = [ 1 , 2 , 6 ]
test_list3 = [ 7 , 9 , 8 ]
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))
res = []
res + = map ( list , zip (test_list1, test_list2, test_list3))
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
test_list1 = [ 3 , 4 , 5 ]
test_list2 = [ 1 , 2 , 6 ]
test_list3 = [ 7 , 9 , 8 ]
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))
res = [ list (sub) for sub in zip (test_list1, test_list2, test_list3)]
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
import numpy as np
test_list1 = [ 3 , 4 , 5 ]
test_list2 = [ 1 , 2 , 6 ]
test_list3 = [ 7 , 9 , 8 ]
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))
res = np.column_stack((test_list1, test_list2, test_list3))
print ( "The matrix after cumulation is : \n" + 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 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
- Create empty list res to store the result.
- Iterate over the indices of the lists using range(len(list)).
- For each index i, create a new empty list row to store the elements at index i from all the given lists.
- Append the element at index i from each list to row.
- Append the completed row to res.
- After iterating through all indices, the res list will contain the required matrix
Python3
test_list1 = [ 3 , 4 , 5 ]
test_list2 = [ 1 , 2 , 6 ]
test_list3 = [ 7 , 9 , 8 ]
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))
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)
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:
- Importing the pandas library using the “import” statement and assigning an alias “pd”.
- Initializing three lists named “test_list1”, “test_list2”, and “test_list3” containing some integer values.
- Creating a DataFrame object by passing a dictionary of lists containing the input lists as values, and using column names as keys.
- Transposing the DataFrame to obtain the desired matrix. Transposing the DataFrame converts rows to columns and vice versa.
- Converting the transposed DataFrame to a nested list using the “.values.tolist()” method of the DataFrame object.
- Printing the result using the “print()” statement, along with a message.
- 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:
Python3
import pandas as pd
test_list1 = [ 3 , 4 , 5 ]
test_list2 = [ 1 , 2 , 6 ]
test_list3 = [ 7 , 9 , 8 ]
df = pd.DataFrame({ 'list1' : test_list1, 'list2' : test_list2, 'list3' : test_list3})
res = df.values.tolist()
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:
- 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.
- Iterate over the input matrix and insert the elements into the empty matrix at the appropriate positions.
- Return the transposed matrix.
Python3
import itertools
test_list1 = [ 3 , 4 , 5 ]
test_list2 = [ 1 , 2 , 6 ]
test_list3 = [ 7 , 9 , 8 ]
matrix = list (itertools.zip_longest(test_list1, test_list2, test_list3))
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)
|
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Apr, 2023
Like Article
Save Article