我是一个初学者。我现在正在sklearn下编写一个特征选择算法,并且编写了一个简单的程序来进行尝试。目标是取出数据集中的某些列,但结果是错误。以下是代码和错误消息。请帮助我,谢谢。我该怎么办?
import numpy as np
from sklearn.datasets import load_iris
data = load_iris()
data=np.array(data)
print(data[:,[0,1]]) #Take the first two columns of the dataset and print
错误消息:
Traceback (most recent call last):
File "K:/b/f_s_DF.py", line 6, in <module>
print(data[:,[0,1]])#Take the first two columns of the dataset and print
IndexError: too many indices for array: array is 0-dimensional, but 2 were indexed
答案 0 :(得分:1)
首先,您需要将虹膜类型<class 'sklearn.utils.Bunch'>
更改为熊猫dataframe
。然后numpy ndarray
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
data1 = np.array(pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= iris['feature_names'] + ['target']))
print(data1[:,:2])
从ndarray获取值时,无需像1,2
这样的索引。您可以给:2
。
答案 1 :(得分:0)
您无需转换Numpy.ndarray
,而是将这些数据转换为pandas Dataframe
,并轻松地看到“拳头两”或任何一栏。请查看以下代码:
import pandas as pd
from sklearn.datasets import load_iris
data = load_iris()
datasets = pd.DataFrame(data['data'], columns =
data['feature_names'])
target_val = pd.Series(data['target'], name =
'target_values')
datasets['target'] = target_val
datasets[:2]
输出:
sepal length sepal width petal length petal width target
0 5.1 3.5 1.4 0.2 0
1 4.9 3.0 1.4 0.2 0