I'm new to sklearn and having trouble formatting the data to predict and evaluate a confusion matrix. I'm using this Random Forest tutorial.

Here is my code

 from sklearn.ensemble import RandomForestClassifier
 import numpy as np
 import pandas as pd
 dataframe = pd.read_csv('output.txt', sep='\t')
 df = pd.DataFrame(dataframe)
 df['is_train'] = np.random.uniform(0, 1, len(df)) <= .75

 train, test = df[df['is_train']==True], df[df['is_train']==False]
 features = df.columns[1:5]
 clf = RandomForestClassifier(n_jobs=2)
 y, _ = pd.factorize(train['event_count'])
 clf.fit(train[features], y)

It's this line for my predictions which is giving me the error:

 preds = df[:6][clf.predict(test[features])]
 IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

1 Answer 1


It is not possible to write numpy style slices in dataframe, like :

observations = data[:6]

Try DataFrame.ix


Cf panda indexing : Panda indexing

  • $\begingroup$ my issue was my 'test' variable did not get exectuted the first time around. so now that works. $\endgroup$
    – Bachzen
    Commented Dec 2, 2016 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.