stephnie
stephnie

Reputation: 1

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [2] of <class 'int'>

I've been learning how to perform PCA in Python, and starting with the tutorial that uses the iris dataset (containing a limited number of features). In this code, it assigned the features to x by specifically naming them like this:

features = ['sepal length', 'sepal width', 'petal length', 'petal width'] 
x = df.loc[:, features].values

I'm now working with my own dataset that has about 270 features, so obviously I can't individually name the features. I've tried assigning the features to x with the following (without assigning the individual features to a variable first):

x = df.loc[:, 2:].values

But I get the error message:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [2] of <class 'int'>

Any thoughts on what I'm doing wrong?

Upvotes: 0

Views: 1891

Answers (1)

Nicolas Gervais
Nicolas Gervais

Reputation: 36684

You're getting this error because the loc takes column names, not integers. For accessing the column at index 2, use iloc:

x = df.iloc[:, 2:].values

Upvotes: 2

Related Questions