Converting two lists into a matrix

Question:

I’ll try to be as clear as possible, and I’ll start by explaining why I want to transform two arrays into a matrix.

To plot the performance of a portfolio vs an market index I need a data structure like in this format:

[[portfolio_value1, index_value1]
 [portfolio_value2, index_value2]]

But I have the the data as two separate 1-D arrays:

portfolio = [portfolio_value1, portfolio_value2, ...]
index = [index_value1, index_value2, ...]

So how do I transform the second scenario into the first. I’ve tried np.insert to add the second array to a test matrix I had in a python shell, my problem was to transpose the first array into a single column matrix.

Any help on how to achieve this without an imperative loop would be great.

Asked By: bitoiu

||

Answers:

Assuming lengths of portfolio and index are the same:

matrix = []
for i in range(len(portfolio)):
    matrix.append([portfolio[i], index[i]])

Or a one-liner using list comprehension:

matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]
Answered By: Joohwan

The standard numpy function for what you want is np.column_stack:

>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
       [2, 5],
       [3, 6]])

So with your portfolio and index arrays, doing

np.column_stack((portfolio, index))

would yield something like:

[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]
Answered By: Jaime

You can use np.c_

np.c_[[1,2,3], [4,5,6]]

It will give you:

np.array([[1,4], [2,5], [3,6]])
Answered By: JY.Yang

Simple you can try this

a=list(zip(portfolio, index))
Answered By: Rohit gupta

You can try the below incase you cant use numpy
Zip wont work for lists of diff length and it returns a tuple and not a list

class Matrix:

def __init__(self, list1, list2):
    self.list1 = list1
    self.list2 = list2
    



def get_mix(self,list1,list2):
        matrix = []
        for elem_one in list1:
            for elem_two in list2 :
                if elem_two:
                    last_elem = elem_two
                    matrix.append([elem_one,elem_two])
                else :
                    
                    matrix.append([elem_one,last_elem])
        
        return matrix

def get_matrix(self):
    returnlist = []
    if len(self.list1) == len(self.list2):
        for elem_one in self.list1:
            for elem_two in self.list2:
                returnlist.append([elem_one,elem_two])
        
        return returnlist 
    

    elif  len(self.list1) > len(self.list2):
        return self.get_mix(self.list1,self.list2)
    
    elif len(self.list1) < len(self.topplist2ings):
        return self.get_mix(self.list2,self.list1)
    
Answered By: Su B
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.