views:

96

answers:

2

I have a 2d array in the numpy module that looks like:

data = array([[1,2,3],
              [4,5,6],
              [7,8,9]])

I want to get a slice of this array that only includes certain columns of element. For example I may want columns 0 and 2:

data = [[1,3],
        [4,6],
        [7,9]]

What is the most Pythonic way to do this? (No for loops please)

I thought this would work, but it results in a "TypeError: list indices must be integers, not tuple"

newArray = data[:,[0,2]]

Thanks.

+3  A: 

Actually, what you wrote should work just fine... What version of numpy are you using?

Just to verify, the following should work perfectly with any recent version of numpy:

import numpy as np
x = np.arange(9).reshape((3,3)) + 1
print x[:,[0,2]]

Which, for me, yields:

array([[1, 3],
       [4, 6],
       [7, 9]])

as it should...

Joe Kington
+4  A: 

The error say it explicitely : data is not a numpy array but a list of lists.

try to convert it to an numpy array first :

numpy.array(data)[:,[0,2]]
BatchyX
Nice catch! I bow to your psychic debugging abilities! :)
Joe Kington