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.
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.
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], ...]
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))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With