The easiest way for getting feature names after running SelectKBest in Scikit Learn
This doesn't require loops.
# Create and fit selectorselector = SelectKBest(f_classif, k=5)selector.fit(features_df, target)# Get columns to keep and create new dataframe with those onlycols = selector.get_support(indices=True)features_df_new = features_df.iloc[:,cols]
You can do the following :
mask = select_k_best_classifier.get_support() #list of booleansnew_features = [] # The list of your K best featuresfor bool, feature in zip(mask, feature_names): if bool: new_features.append(feature)
Then change the name of your features:
dataframe = pd.DataFrame(fit_transofrmed_features, columns=new_features)
For me this code works fine and is more 'pythonic':
mask = select_k_best_classifier.get_support()new_features = features_dataframe.columns[mask]