从熊猫数据框中识别特征名称

时间:2020-07-01 08:12:59

标签: python

我有一段代码如下:

# transforming data to best 20 features
from sklearn.feature_selection import SelectKBest, chi2
import matplotlib.pyplot as plt
fs = SelectKBest(score_func=chi2, k=20)
fs.fit(X_train, y_train)
X_train = fs.transform(X_train)
X_test = fs.transform(X_test)



# what are scores for the features
for i in range(len(fs.scores_)):
print('Feature %d: %f' % (i, fs.scores_[i]))
# plot the scores
plt.bar([i for i in range(len(fs.scores_))], fs.scores_)
plt.show()

该图为我提供了this picture中所示的输出,我想知道如何识别这些特征的实际特征名称而不是“ 1-20”?我尝试了get_support(),但由于我使用train_test_split时数据为数组格式,因此出现了错误。

1 个答案:

答案 0 :(得分:0)

这些功能与X_train数组中的数据的顺序相同。因此,为了获得功能名称,应在将X_train制作为numpy数组之前将其提取。如果您使用的是名为df的熊猫数据框,则可以执行以下操作:

for i in range(len(fs.scores_)):
    print(f'Feature {df.columns[i]}: {fs.scores_[i]}')