将 DataFrame 的行索引保持在方差阈值转换

Keep row indices of DataFrame at Variance Threshold transformation

我正在 pandas DataFrame 上使用 sklearn 进行方差阈值特征选择。为了避免特征选择的偏差——VarianceThreshold 只是第一步——我将原始数据集分成了一部分用于特征选择(X_selection, y_selection)和建模部分(X_model, y_model)。然而,它们包含相同顺序的相同列。所以,我从定义选择器开始,然后拟合数据:

# get column names
X_columns = X_selection.columns

# doing the variance threshold feature selection
selector = VarianceThreshold()
selector.fit(X_selection)

# filtering the selected column names
X_columns = X_columns[selector.get_support()]

# transform original data according to selector
X_selection = pd.DataFrame(selector.transform(X_selection), columns = X_columns)
X_model = pd.DataFrame(selector.transform(X_model), columns = X_columns)

不幸的是,我遇到了结果 X_selection[= 中的行21=]X_model乱七八糟。例如,在转换之前,我得到了 X_model:

中的一些示例性行
        COL_X
0       0.000000
1       0.000000
2       0.000000
10      0.000000
25      0.185185
150     0.037037
3333    0.000000
16000   0.000000

转换后,调用X_model的同一行索引得到:

        COL_X
0       0.000000
1       0.000000
2       0.111111
10      0.000000
25      0.000000
150     0.000000
3333    0.000000
16000   0.111111

据我所知,transform 以我不知道的方式对行进行了洗牌。虽然与带有 class 标签的 y_model 数组的关系被破坏了,因为行的顺序在这里没有改变。感谢您对如何修复它或隐藏我的错误的任何评论。

我不知道的事实是,pandas 将新的索引(从 0 开始,递增 1)分配给 DataFrame,同时将转换的结果数组再次转换为 pandas DataFrame :

X_model = pd.DataFrame(selector.transform(X_model), columns = X_columns)

当请求具有 "old" 行索引的行的子集时,这会给出与以前不同的值。所以,顺序还是一样的。但是,我想保留原始行索引。因此,我现在根据仍然保留在 y_model.

中的旧索引设置索引
X_model = X_model.set_index(y_model.index)