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.
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]])
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))]
Simple you can try this
a=list(zip(portfolio, index))
Source: Stackoverflow.com