sklearn.decomposition.PCA explained_variance_ratio_ attribute does not exist When trying to identify the variance explained by the first two columns of my dataset using the explained_variance_ratio_ attribute of sklearn.decomposition.PCA I recieve the following error:

AttributeError: 'PCA' object has no attribute 'explained_variance_ratio_'


My code (condensed):

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

df = pd.read_csv('Input.csv')
df = df.dropna()
df_transform = StandardScaler().fit_transform(df)
pca = PCA(n_components=2).fit_transform(df_transform)
var_exp = pca.explained_variance_ratio_


When the last line is executed, I get the error:

AttributeError: 'PCA' object has no attribute 'explained_variance_ratio_'


I am using sklearn version 0.20.0

Edit

After examining the attributes of sklearn.decomposition.PCA, I see that the attribute does indeed not exist (as shown in image).
This is untested, but I believe the error is occurring because you're calling explained variance on the fit_transform object, as opposed to simply just the results of fit.

Try:

df = pd.read_csv('Input.csv')
df = df.dropna()
df_transform = StandardScaler().fit_transform(df)
pca = PCA(n_components=2).fit(df_transform)
new_df = pca.transform(df_transform)
var_exp = pca.explained_variance_ratio_