[英]matrices are not aligned error message
I have the following dataframe of returns我有以下 dataframe 的回报
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我不确定为什么会收到此错误,但很乐意为加权回报提供替代解决方案
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
For a dot product of dataframe dfA by dataframe dfB, the column names of dfA must coincide with the index of dfB, otherwise you'll get the error 'ValueError: matrices are not aligned'对于 dataframe dfA 与 dataframe dfB 的点积,dfA 的列名必须与 dfB 的索引一致,否则会出现错误“ValueError: matrices are not aligned”
dfA = pd.DataFrame( data = [[1, 2], [3, 4], [5, 6]], columns=['one', 'two'])
dfB = pd.DataFrame( data = [[1, 2, 3], [4, 5, 6]], index=['one', 'two'])
dfA.dot(dfB)
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. 仅当A的第二轴与B的第一轴具有相同的大小时,才可以计算矩阵
A.dot(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. 尝试运行
port_ret = ret[:,1:].dot(df3[1:])
然后检查它是否产生所需的结果。
For future cases, use numpy.shape()
function to debug matrix calculations, it is really helpful tool. 对于将来的情况,请使用
numpy.shape()
函数调试矩阵计算,这确实是有用的工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.