如何切片 2D Python 数组?失败:“类型错误:列表索引必须是整数,而不是元组”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3680262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to slice a 2D Python Array? Fails with: "TypeError: list indices must be integers, not tuple"
提问by Jonathan
I have a 2d array in the numpy module that looks like:
我在 numpy 模块中有一个二维数组,如下所示:
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:
我想得到这个数组的一部分,它只包含某些元素列。例如,我可能想要第 0 列和第 2 列:
data = [[1,3],
[4,6],
[7,9]]
What is the most Pythonic way to do this? (No for loops please)
什么是最 Pythonic 的方式来做到这一点?(请不要循环)
I thought this would work:
我认为这会奏效:
newArray = data[:,[0,2]]
but it results in a:
但结果是:
TypeError: list indices must be integers, not tuple
回答by Joe Kington
Actually, what you wrote should work just fine... What version of numpy are you using?
实际上,您写的内容应该可以正常工作...您使用的是什么版本的 numpy?
Just to verify, the following should work perfectly with any recent version of numpy:
只是为了验证,以下内容应该适用于任何最新版本的 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...
正如它应该...
回答by BatchyX
The error say it explicitely : data is not a numpy array but a list of lists.
错误明确指出:数据不是一个numpy数组,而是一个列表列表。
try to convert it to an numpy array first :
首先尝试将其转换为 numpy 数组:
numpy.array(data)[:,[0,2]]
回答by Superseb694
Beware that numpy only accept regular array with the same size for each elements.
you can somehow use :
[a[i][0:2] for i in xrange(len(a))]it's pretty ugly but it works.
请注意,numpy 只接受每个元素具有相同大小的常规数组。你可以以某种方式使用:
[a[i][0:2] for i in xrange(len(a))]它很丑,但它有效。
回答by Mac D
THis may not be what you are looking for but this is would do. zip(*x)[whatever columns you might need]
这可能不是你要找的,但这是可以的。zip(*x)[您可能需要的任何列]
回答by SKIL
If you'd want to slice 2D listthe following function may help
如果您想切片 2D列表,以下功能可能会有所帮助
def get_2d_list_slice(self, matrix, start_row, end_row, start_col, end_col):
return [row[start_col:end_col] for row in matrix[start_row:end_row]]
回答by FartVader
newArray = data[:,0:2]
or am I missing something?
或者我错过了什么?

