Python 将两个列表转换为矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18730044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting two lists into a matrix
提问by bitoiu
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.
那么我如何将第二个场景转换为第一个场景。我试图np.insert
将第二个数组添加到我在 python shell 中的测试矩阵中,我的问题是将第一个数组转置为单列矩阵。
Any help on how to achieve this without an imperative loop would be great.
关于如何在没有命令式循环的情况下实现这一点的任何帮助都会很棒。
采纳答案by Jaime
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
所以用你的portfolio
和index
数组,做
np.column_stack((portfolio, index))
would yield something like:
会产生类似的东西:
[[portfolio_value1, index_value1],
[portfolio_value2, index_value2],
[portfolio_value3, index_value3],
...]
回答by Joohwan
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))]
回答by JY.Yang
You can use np.c_
你可以使用 np.c_
np.c_[[1,2,3], [4,5,6]]
np.c_[[1,2,3], [4,5,6]]
It will give you:
它会给你:
np.array([[1,4], [2,5], [3,6]])