Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting two lists into a matrix

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.

like image 532
bitoiu Avatar asked Sep 10 '13 22:09

bitoiu


People also ask

How do I create a NumPy array from two lists?

On passing a list of list to numpy. array() will create a 2D Numpy Array by default. But if we want to create a 1D numpy array from list of list then we need to merge lists of lists to a single list and then pass it to numpy. array() i.e.


2 Answers

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],  ...] 
like image 109
Jaime Avatar answered Sep 21 '22 09:09

Jaime


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))] 
like image 26
Joohwan Avatar answered Sep 23 '22 09:09

Joohwan