I am trying to use a principal component analysis to determine the most important features in my dataset. When I run the code below, I receive an error saying "PCA object is not subscribable." I have attempted to add various arguments into the PCA() function but receive the same error any time.

from sklearn.decomposition import PCA

pca =   PCA()
x_pca = pca.fit(X_train)

def myplot(score,coeff,labels=None):
    xs = score[:,0]
    ys = score[:,0]
    n = coeff.shape[0]
    scalex = 1.0/(xs.max() - xs.min())
    scaley = 1.0/(ys.max() - ys.min())
    plt.scatter(xs * scalex,ys * scaley, c = y)
    for i in range(n):
        plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)
        if labels is None:
            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')
            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')

#Call the function. Use only the 2 PCs.
myplot(x_pca[:,0:2],np.transpose(pca.components_[0:2, :]))
  • $\begingroup$ Please note that PCA stands for Principal Component Analysis $\endgroup$
    – noe
    Feb 9, 2023 at 15:59

1 Answer 1


The issue is caused by the fact that you are trying to index the PCA object when calling x_pca[:,0:2]. I am not sure what type of values you are expecting to pass to your myplot function, but calling PCA.fit does not return an array of values but simply the PCA instance itself (see also the documentation). If you are looking to use the values on the new principal components you can use the transform method after having fitted the PCA object, or use the fit_transform method to fit and transform the data in a single step.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.