pandas 矩阵未对齐错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39322928/
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
matrices are not aligned error message
提问by John
I have the following dataframe of returns
我有以下返回数据框
ret
Out[3]:
Symbol FX OGDC PIB WTI
Date
2010-03-02 0.000443 0.006928 0.000000 0.012375
2010-03-03 -0.000690 -0.007873 0.000171 0.014824
2010-03-04 -0.001354 0.001545 0.000007 -0.008195
2010-03-05 -0.001578 0.008796 -0.000164 0.015955
And the following weights for each symbol:
以及每个符号的以下权重:
df3
Out[4]:
Symbol Weight
0 OGDC 0.182022
1 WTI 0.534814
2 FX 0.131243
3 PIB 0.151921
I am trying to get a weighted return for each day and tried:
我试图获得每天的加权回报并尝试:
port_ret = ret.dot(df3)
but I get the following error message:
但我收到以下错误消息:
ValueError: matrices are not aligned
My objective is to have a weighted return for each date such that, for example 2010-03-02 would be as follows:
我的目标是对每个日期进行加权回报,例如 2010-03-02 如下:
weighted_ret = 0.000443*.131243+.006928*.182022+0.000*0.151921+0.012375*.534814 = 0.007937512
I am not sure why I am getting this error but would be very happy for an alternative solution to the weighted return
我不确定为什么我会收到此错误,但会很高兴为加权回报提供替代解决方案
回答by Boud
You have two columns in your weight matrix:
您的权重矩阵中有两列:
df3.shape
Out[38]: (4, 2)
Set the index to Symbol
on that matrix to get the proper dot
:
将索引设置Symbol
为该矩阵以获得正确的dot
:
ret.dot(df3.set_index('Symbol'))
Out[39]:
Weight
Date
2010-03-02 0.007938
2010-03-03 0.006430
2010-03-04 -0.004278
2010-03-05 0.009902
回答by fulaphex
Check the shape of the matrices you're calling the dot product on. The dot product of matrices A.dot(B)
can be computed only if second axis of A is the same size as first axis of B.
In your example you have additional column with date, that ruins your computation. You should just get rid of it in your computation. Try running port_ret = ret[:,1:].dot(df3[1:])
and check if it produces the result you desire.
For future cases, use numpy.shape()
function to debug matrix calculations, it is really helpful tool.
检查您调用点积的矩阵的形状。A.dot(B)
只有当 A 的第二个轴与 B 的第一个轴的大小相同时,才能计算矩阵的点积。
在您的示例中,您有额外的日期列,这会破坏您的计算。你应该在你的计算中摆脱它。尝试运行port_ret = ret[:,1:].dot(df3[1:])
并检查它是否产生您想要的结果。
对于未来的情况,使用numpy.shape()
函数来调试矩阵计算,它真的是很有用的工具。