将两个列表转换为矩阵 [英] Converting two lists into a matrix
问题描述
我会尽量说清楚,然后我会先解释为什么我要将两个数组转换为矩阵.
要绘制投资组合与市场指数的表现,我需要一个类似以下格式的数据结构:
[[portfolio_value1, index_value1][portfolio_value2, index_value2]]
但我将数据作为两个单独的一维数组:
portfolio = [portfolio_value1,portfolio_value2, ...]index = [index_value1, index_value2, ...]
那么我如何将第二个场景转换为第一个场景.我试过 np.insert
将第二个数组添加到我在 python shell 中的测试矩阵中,我的问题是将第一个数组转置为单列矩阵.
关于如何在没有命令式循环的情况下实现这一目标的任何帮助都会很棒.
你想要的标准 numpy 函数是 np.column_stack
:
所以用你的 portfolio
和 index
数组,做
np.column_stack((portfolio, index))
会产生类似:
[[portfolio_value1, index_value1],[portfolio_value2, index_value2],[portfolio_value3, index_value3],...]
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.
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],
...]
这篇关于将两个列表转换为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!