1

I came across this code in Python:

processed = data[:,feature_locs]

I tried testing this sort of code out with this

    ha = (3, 5, 7)
    print ha
    data = [1, 2, 3, 4, 5]
    print data[:, ha]

but I get a TypeError.

What am I doing wrong, and what does the above syntax mean?

2
  • 3
    Where did you spot the first snippet? Commented Mar 9, 2014 at 21:33
  • 2
    Looks like a 2-dimensional index as used by numpy Commented Mar 9, 2014 at 21:36

2 Answers 2

4

This is a custom slice argument supported by the numpy module for multidimensional arrays.

>>> import numpy
>>> a = numpy.random.random((2,3))
>>> a
array([[ 0.01211291,  0.06738324,  0.11690497],
       [ 0.86175703,  0.21903569,  0.49506358]])
>>> a[:,1]
array([ 0.06738324,  0.21903569])

See the numpy documentation for more details http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

Sign up to request clarification or add additional context in comments.

Comments

4

when you are working with a 2 dimensional array (or list of lists) using this syntax addresses the whole first dimension and the range specified in the second argument. as such -

s = [11, 12, 13, 14]
s2 = [21, 22, 23, 24]
s3 = [s, s2] # List of lists
s4 = array(s3) # 2-dimensional array

print s4[:,1:3]
-> [[12, 13],
    [22, 23]]

as you can see, this runs over the first dimension entirely and prints the second and third element of the second dimensions

EDIT: as mentioned by @tobias_k in the comments - the array() function is provided by the numpy package so you need to add a proper import for it. this syntax is provided by the package for 2-dimensional arrays and not for ordinary list-of-lists.

1 Comment

You should add that array is a function from the numpy package. It does not work with "ordinary" lists of lists.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.