将两个列表转换为矩阵

时间:2022-06-20 01:54:11

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:

但我将数据作为两个独立的1-D阵列:

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.

那么如何将第二个场景转换为第一个场景。我已经尝试过np.insert将第二个数组添加到我在python shell中的测试矩阵中,我的问题是将第一个数组转换为单个列矩阵。

Any help on how to achieve this without an imperative loop would be great.

如果没有命令性循环如何实现这一点的任何帮助将是伟大的。

2 个解决方案

#1


39  

The standard numpy function for what you want is np.column_stack:

你想要的标准numpy函数是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],
 ...]

#2


1  

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

#1


39  

The standard numpy function for what you want is np.column_stack:

你想要的标准numpy函数是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],
 ...]

#2


1  

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