我正在尝试使用函数pandas.ewm.cov()计算一组数据之间的指数加权协方差。听起来很傻,但是我在访问结果时遇到了麻烦:特别是如何获取作为熊猫数据帧的最后一个矩阵(在本示例中为第999个)(切片等似乎也会影响内部索引0、1、2)。有谁能提供高效且可扩展的解决方案?
import pandas as pd
import numpy as np
if __name__ == "__main__":
df = pd.DataFrame(np.random.randn(1000, 3))
covs = df.ewm(span = 180).cov()
print(covs)
print(covs.iloc[-3:,:]) #this does not work anymore If I change the
# dimension of the df from 3 i.e. to 4.
0 1 2
0 0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
1 0 0.032264 -0.163599 -0.125954
1 -0.163599 0.829545 0.638665
2 -0.125954 0.638665 0.491707
... ... ... ...
999 0 0.878615 0.011006 0.157368
1 0.011006 0.905043 0.078750
2 0.157368 0.078750 1.058194
-----------------------------------
0 1 2
999 0 1.160964 0.030447 -0.030059
1 0.030447 0.880037 0.048503
2 -0.030059 0.048503 0.975215
编辑:刚刚提出了以下解决方案。任何有关清洁和/或直接清洁的建议都将受到赞赏。
import pandas as pd
import numpy as np
if __name__ == "__main__":
df = pd.DataFrame(np.random.randn(1000, col = 3))
covs = df.ewm(span = 180).cov()
covs = covs.iloc[-len(df.columns):]
covs = covs.reset_index(level = 0, drop = True)
print(covs)