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
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.
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 .
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.
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)] .
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With