title: Cumulative Explained Variance for PCA in Python
body: <p>I have a simple R script for running <a href="http://factominer.free.fr/classical-methods/principal-components-analysis.html" rel="nofollow noreferrer">FactoMineR's PCA</a> on a tiny dataframe in order to find the cumulative percentage of variance explained for each variable:</p>
  
  <pre><code>library(FactoMineR)
  a &lt;- c(1, 2, 3, 4, 5)
  b &lt;- c(4, 2, 9, 23, 3)
  c &lt;- c(9, 8, 7, 6, 6)
  d &lt;- c(45, 36, 74, 35, 29)
  
  df &lt;- data.frame(a, b, c, d)
  
  df_pca &lt;- PCA(df, ncp = 4, graph=F)
  print(df_pca$eig$`cumulative percentage of variance`)
  </code></pre>
  
  <p>Which returns: </p>
  
  <pre><code>&gt; print(df_pca$eig$`cumulative percentage of variance`)
  [1]  58.55305  84.44577  99.86661 100.00000
  </code></pre>
  
  <p>I'm trying to do the same in Python using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html" rel="nofollow noreferrer">scikit-learn's decomposition package</a> as follows: </p>
  
  <pre><code>import pandas as pd
  from sklearn import decomposition, linear_model
  
  a = [1, 2, 3, 4, 5]
  b = [4, 2, 9, 23, 3]
  c = [9, 8, 7, 6, 6]
  d = [45, 36, 74, 35, 29]
  
  df = pd.DataFrame({'a': a,
                    'b': b,
                    'c': c, 
                    'd': d})
  
  pca = decomposition.PCA(n_components = 4)
  pca.fit(df)
  transformed_pca = pca.transform(df)
  
  # sum cumulative variance from each var
  cum_explained_var = []
  for i in range(0, len(pca.explained_variance_ratio_)):
      if i == 0:
          cum_explained_var.append(pca.explained_variance_ratio_[i])
      else:
          cum_explained_var.append(pca.explained_variance_ratio_[i] + 
                                   cum_explained_var[i-1])
  print(cum_explained_var)
  </code></pre>
  
  <p>But this results in:</p>
  
  <pre><code>[0.79987089715487936, 0.99224337624509307, 0.99997254568237226, 1.0]
  </code></pre>
  
  <p>As you can see, both correctly add up to 100%, but it seems the contributions of each variable differ between the R and Python versions. Does anyone know where these differences are coming from or how to correctly replicate the R results in Python?</p>
  
  <p>EDIT: Thanks to Vlo, I now know that the differences stem from the FactoMineR PCA function scaling the data by default. By using the sklearn preprocessing package (pca_data = preprocessing.scale(df)) to scale my data before running PCA, my results match the </p>