选择要素后打印列/变量名称

2024-06-16 14:57:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Iris dateset上尝试功能选择

我指的是Feature Selection with Univariate Statistical Tests

我正在使用下面的行,我想找出重要的功能:

import pandas
from pandas import read_csv
from numpy import set_printoptions
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif

dataframe = pandas.read_csv("C:\\dateset\\iris.csv"]))
array = dataframe.values
X = array[:,0:4]
Y = array[:,4]

test = SelectKBest(score_func=f_classif, k=2)
fit = test.fit(X, Y)

set_printoptions(precision=2)
arr = fit.scores_

print (arr)

# [ 119.26   47.36 1179.03  959.32]

为了通过得分显示前2名的索引,我添加了:

idx = (-arr).argsort()[:2]
print (idx)

# [2 3]

此外,如何获得列/变量名(而不是它们的索引)


Tags: csvfromimport功能pandasreadsklearnarray
2条回答
import pandas
from pandas import read_csv
from numpy import set_printoptions
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif

dataframe = pandas.read_csv("iris.csv")
array = dataframe.values
X = array[:,0:4]
Y = array[:,4]

test = SelectKBest(score_func=f_classif, k=2)
fit = test.fit(X, Y)

set_printoptions(precision=2)
arr = fit.scores_

idx = (-arr).argsort()[:2]
print (idx)

print (arr)
#names=[dataframe.columns[j] for j in X]

names = dataframe.columns[idx]
print(names)

输出

[2 3]
[ 119.26   47.36 1179.03  959.32]
Index(['petal_length', 'petal_width'], dtype='object')

使用索引,这里可以使用列名称,因为选择了前4列:

#first 4 columns
X = array[:,0:4]

cols = dataframe.columns[idx]

如果对X的选择不同,则还需要使用变量按位置数据帧进行筛选:

#e.g. selected 3. to 7. column
X = array[:,2:6]

cols = dataframe.iloc[:, 2:6].columns[idx]

相关问题 更多 >