如何从 python 中的协方差矩阵获取子协方差
How can I get a subcovariance from a covariance matrix in python
我在 python 中有一个协方差矩阵(作为 pandas DataFrame)如下:
a b c
a 1 2 3
b 2 10 4
c 3 4 100
我只想动态地 select 矩阵协方差的一个子集。例如 A 和 C 的子集看起来像
a c
a 1 3
c 3 100
有什么函数可以select这个子集吗?
谢谢!
如果您的协方差矩阵是这样的 numpy 数组:
cov = np.array([[1, 2, 3],
[2, 10, 4],
[3, 4, 100]])
然后可以通过advanced indexing得到想要的子矩阵:
subset = [0, 2] # a, c
cov[np.ix_(subset, subset)]
# array([[ 1, 3],
# [ 3, 100]])
编辑:
如果您的协方差矩阵是 pandas DataFrame(例如,对于某些列为 'a', 'b', 'c', ...
的数据帧 df
,作为 cov = df.cov()
获得),以获得 [=16 的子集=] 和 'c'
您可以执行以下操作:
cov.loc[['a','c'], ['a','c']]
我在 python 中有一个协方差矩阵(作为 pandas DataFrame)如下:
a b c
a 1 2 3
b 2 10 4
c 3 4 100
我只想动态地 select 矩阵协方差的一个子集。例如 A 和 C 的子集看起来像
a c
a 1 3
c 3 100
有什么函数可以select这个子集吗?
谢谢!
如果您的协方差矩阵是这样的 numpy 数组:
cov = np.array([[1, 2, 3],
[2, 10, 4],
[3, 4, 100]])
然后可以通过advanced indexing得到想要的子矩阵:
subset = [0, 2] # a, c
cov[np.ix_(subset, subset)]
# array([[ 1, 3],
# [ 3, 100]])
编辑:
如果您的协方差矩阵是 pandas DataFrame(例如,对于某些列为 'a', 'b', 'c', ...
的数据帧 df
,作为 cov = df.cov()
获得),以获得 [=16 的子集=] 和 'c'
您可以执行以下操作:
cov.loc[['a','c'], ['a','c']]