将两个列表转换成矩阵

问题描述:

我会尽量保持清晰,我将首先解释为什么要将两个数组转换为矩阵.

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

那么我该如何将第二种情况转换为第一种情况.我试过np.insert将第二个数组添加到我在python shell中拥有的测试矩阵中,我的问题是将第一个数组转置为单个列矩阵.

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.

所需的标准numpy函数是np.column_stack:

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

所以对于您的portfolioindex数组,做

So with your portfolio and index arrays, doing

np.column_stack((portfolio, index))

会产生类似以下内容:

[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]