使用pandas数据帧进行主成分分析

时间:2014-04-25 00:22:48

标签: python pandas pca scientific-computing principal-components

如何根据pandas数据框中的数据计算主成分分析?

2 个答案:

答案 0 :(得分:67)

大多数sklearn个对象都可以使用pandas个数据帧,这样会对你有用吗?

import pandas as pd
import numpy as np
from sklearn.decomposition import PCA

df = pd.DataFrame(data=np.random.normal(0, 1, (20, 10)))

pca = PCA(n_components=5)
pca.fit(df)

您可以使用

访问组件
pca.components_ 

答案 1 :(得分:1)

import pandas
from sklearn.decomposition import PCA
import numpy
import matplotlib.pyplot as plot

df = pandas.DataFrame(data=numpy.random.normal(0, 1, (20, 10)))

# You must normalize the data before applying the fit method
df_normalized=(df - df.mean()) / df.std()
pca = PCA(n_components=df.shape[1])
pca.fit(df_normalized)

# Reformat and view results
loadings = pandas.DataFrame(pca.components_.T,
columns=['PC%s' % _ for _ in range(len(df_normalized.columns))],
index=df.columns)
print(loadings)

plot.plot(pca.explained_variance_ratio_)
plot.ylabel('Explained Variance')
plot.xlabel('Components')
plot.show()