Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice a 2D Python Array? Fails with: "TypeError: list indices must be integers, not tuple"

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:

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

but it results in a:

TypeError: list indices must be integers, not tuple
like image 513
Jonathan Avatar asked Sep 09 '10 20:09

Jonathan


People also ask

How do I fix list indices must be integers or slices not tuple in Python?

The Python "TypeError: list indices must be integers or slices, not tuple" occurs when we pass a tuple between the square brackets when accessing a list at index. To solve the error, make sure to separate nested list elements with commas and correct the index accessor.

How do you slice a 2d array in Python?

To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .

How do you fix tuple indices must be integers or slices not tuple?

You are likely to encounter an error called typeerror list indices must be integers or slices, not tuple. The only way to resolve this situation is to pass in an integer in a slice as the indices while performing any operation using lists.

How do you fix list indices must be integers or slices not float?

The Python "TypeError: list indices must be integers or slices, not float" occurs when we use a floating-point number to access a list at a specific index. To solve the error, convert the float to an integer, e.g. my_list[int(my_float)] .


1 Answers

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]]
like image 55
BatchyX Avatar answered Sep 28 '22 20:09

BatchyX