41
votes

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.

4

4 Answers

89
votes

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],
 ...]
3
votes

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))]
3
votes

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]])
1
votes

Simple you can try this

a=list(zip(portfolio, index))