Retain feature names after Scikit Feature Selection
<p>After running a Variance Threshold from Scikit-Learn on a set of data, it removes a couple of features. I feel I'm doing something simple yet stupid, but I'd like to retain the names of the remaining features. The following code: </p>

<pre><code>def VarianceThreshold_selector(data):
    selector = VarianceThreshold(.5) 
    selector.fit(data)
    selector = (pd.DataFrame(selector.transform(data)))
    return selector
x = VarianceThreshold_selector(data)
print(x)
</code></pre>

<p>changes the following data (this is just a small subset of the rows):</p>

<pre><code>Survived    Pclass  Sex Age SibSp   Parch   Nonsense
0             3      1  22   1        0        0
1             1      2  38   1        0        0
1             3      2  26   0        0        0
</code></pre>

<p>into this (again just a small subset of the rows)</p>

<pre><code>     0         1      2     3
0    3      22.0      1     0
1    1      38.0      1     0
2    3      26.0      0     0
</code></pre>

<p>Using the get_support method, I know that these are Pclass, Age, Sibsp, and Parch, so I'd rather this return something more like :</p>

<pre><code>     Pclass         Age      Sibsp     Parch
0        3          22.0         1         0
1        1          38.0         1         0
2        3          26.0         0         0
</code></pre>

<p>Is there an easy way to do this? I'm very new with Scikit Learn, so I'm probably just doing something silly. </p>

<p>Would something like this help? If you pass it a pandas dataframe, it will get the columns and use <code>get_support</code> like you mentioned to iterate over the columns list by their indices to pull out only the column headers that met the variance threshold.</p>

<pre><code>&gt;&gt;&gt; df
   Survived  Pclass  Sex  Age  SibSp  Parch  Nonsense
0         0       3    1   22      1      0         0
1         1       1    2   38      1      0         0
2         1       3    2   26      0      0         0
&gt;&gt;&gt; def VarianceThreshold_selector(data):
    columns = data.columns
    selector = VarianceThreshold(.5)
    selector.fit_transform(data)
    labels = [columns[x] for x in selector.get_support(indices=True) if x]
    return pd.DataFrame(selector.fit_transform(data), columns=labels)

&gt;&gt;&gt; VarianceThreshold_selector(df)
   Pclass  Age
0       3   22
1       1   38
2       3   26
</code></pre>

python pandas scikit-learn output feature-selection