首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算数据帧的协方差矩阵

如何计算数据帧的协方差矩阵
EN

Stack Overflow用户
提问于 2019-04-28 22:31:10
回答 3查看 4.1K关注 0票数 0

我已经读取了数据框架的传感器数据,使用熊猫read_fwf功能。我需要找到读928991 x 8矩阵的协方差矩阵。最后,我想找出本征向量和特征值,使用主成分分析算法对这个协方差矩阵。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-04-30 04:57:08

这个问题的答案如下

代码语言:javascript
复制
import pandas as pd
import numpy as np
from numpy.linalg import eig

df_sensor_data = pd.read_csv('HT_Sensor_dataset.dat', delim_whitespace=True)
del df_sensor_data['id']
del df_sensor_data['time']
del df_sensor_data['Temp.']
del df_sensor_data['Humidity']
df = df_sensor_data.notna().astype('float64')
covariance_matrix = df_sensor_data.cov()
print(covariance_matrix)

values, vectors = eig(covariance_matrix)
print(values)
print(vectors)
票数 1
EN

Stack Overflow用户

发布于 2019-04-28 22:46:59

首先,您需要使用df.values将熊猫数据放到一个numpy数组中。例如:

代码语言:javascript
复制
A = df.values

在将数据放入数字数组之后,计算协方差矩阵或PCA将非常容易。欲了解更多情况:

代码语言:javascript
复制
# import functions you need to compute covariance matrix from numpy
from numpy import array
from numpy import mean
from numpy import cov
from numpy.linalg import eig

# assume you load your data using pd.read_fwf to variable *df*
df = pd.read_fwf(filepath, widths=col_widths, names=col_names)
#put dataframe values to a numpy array
A = df.values
#check matrix A's shape, it should be (928991, 8)
print(A.shape)
# calculate the mean of each column
M = mean(A.T, axis=1)
print(M)
# center columns by subtracting column means
C = A - M
print(C)
# calculate covariance matrix of centered matrix
V = cov(C.T)
print(V)
# eigendecomposition of covariance matrix
values, vectors = eig(V)
print(vectors)
print(values)
# project data
P = vectors.T.dot(C.T)
print(P.T)

运行该示例,首先输出原始矩阵,然后是中心协方差矩阵的特征向量和特征值,然后是原始矩阵的投影。这里有一个链接,您可能会发现对您的PCA任务有用。

票数 2
EN

Stack Overflow用户

发布于 2019-04-28 23:03:44

为什么不直接使用pd.DataFrame.cov 函数

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55895097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档