Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a list of indices to another list in Python. Correct syntax?

Tags:

python

syntax

So I have the following code from sklearn:

>>> from sklearn import cross_validation
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4])
>>> kf = cross_validation.KFold(4, n_folds=2)
>>> len(kf)
2
>>> print(kf)  
sklearn.cross_validation.KFold(n=4, n_folds=2, shuffle=False,
                           random_state=None)
>>> for train_index, test_index in kf:
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [0 1] TEST: [2 3]
.. automethod:: __init__

It gives me an error when I pass on the train_index and the test_index in these lines of code (IndexError: indices are out-of-bounds):

...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]

Why can't I pass a list of indices to a list? What is the correct syntax to pass a list of indices to another list to get those elements of that list?

I am using Python 2.7.

Thanks.

like image 601
jenny Avatar asked Sep 17 '25 18:09

jenny


2 Answers

Unlike Numpy arrays, python lists don't support accessing by multiple indexes.

It's easy to solve using list comprehensions, though:

l= range(10)
indexes= [1,3,5]
result= [l[i] for i in indexes]

Or the slighly less readable (but more useful in some occasions) map:

result= map(l.__getitem__, indexes)

However, as Ashwini Chaudhary noted, X and y are numpy arrays in your example, so you either entered the wrong example code or your particular indexes indeed are out of range.

like image 185
loopbackbee Avatar answered Sep 20 '25 07:09

loopbackbee


you could also use :

res_list = list(itemgetter(*index_list)(test_list)) 

Edit: here is an example

>>> import operator
>>> indices = [1, 3, 4]
>>> list(operator.itemgetter(*indices)(range(10)))
[1, 3, 4]
like image 40
Damien Lancry Avatar answered Sep 20 '25 08:09

Damien Lancry