【问题标题】:Printing column/variable names after feature selection选择特征后打印列/变量名
【发布时间】:2021-01-28 11:39:20
【问题描述】:

我正在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]

此外,我怎样才能获得列/变量名称(而不是它们的索引)?

【问题讨论】:

    标签: python pandas dataframe feature-selection


    【解决方案1】:

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

    #first 4 columns
    X = array[:,0:4]
    
    cols = dataframe.columns[idx]
    

    如果 X 变量的选择不同,则还需要按位置 DataFrame 过滤:

    #e.g. selected 3. to 7. column
    X = array[:,2:6]
    
    cols = dataframe.iloc[:, 2:6].columns[idx]
    

    【讨论】:

    • 太棒了,先生!谢谢你,很高兴再次得到你的指导!
    【解决方案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')
    
    

    【讨论】:

      猜你喜欢
      • 2014-09-12
      • 2012-12-17
      • 2014-02-27
      • 2021-04-27
      • 2020-08-25
      • 2017-02-10
      • 2017-06-03
      • 2013-02-20
      • 1970-01-01
      相关资源
      最近更新 更多