首页 > 解决方案 > ValueError:项目错误长度 0 而不是 150。同时从数据框中提取值

问题描述

数据集如下

5.1,3.5,1.4,0.2,setosa 
4.9,3.0,1.4,0.2,setosa 
4.7,3.2,1.3,0.2,setosa 
4.6,3.1,1.5,0.2,setosa

代码如下

df = pd.read_csv('iris.data.csv',header=None,sep=',')
df.columns = ['Sep Len','Sep Wid','Pet Len','Pet Wid','Species']
X = df.iloc[:0:4].values
y = df.iloc[:4].values
Sepal_Width  = X[:1]
iris_outliers = Sepal_Width > 4
df[iris_outliers]

df[iris_outliers]必须打印return the dataframe if Sep Wid(X[:1]) > 4

我收到错误 ValueError: Item wrong length 0 而不是 150。

标签: pandas

解决方案


我认为问题在于选择第二个'column'- 需要:所有行,然后是逗号并4选择最后第五列:

cols = ['Sep Len','Sep Wid','Pet Len','Pet Wid','Species']
df = pd.read_csv('iris.data.csv', names=cols)

X = df.iloc[:,4].values
print (X)
['setosa' 'setosa' 'setosa' 'setosa']

或查看最后一栏:

X = df.iloc[:,-1].values

类似y

y = df.iloc[:,:4].values

y = df.iloc[:, :-1].values
print (y)
[[5.1 3.5 1.4 0.2]
 [4.9 3.  1.4 0.2]
 [4.7 3.2 1.3 0.2]
 [4.6 3.1 1.5 0.2]]

推荐阅读