[英]Slicing a 2D numpy array in python
What's wrong with the code below? 下面的代码有什么问题?
arr=numpy.empty((2,2))
arr[0:,0:]=1
print(arr[1:,1:])
arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
print(arr[1:2, 1])
I am getting the following error and not able to slice the array( fifth line). 我收到以下错误,无法切片数组(第五行)。 Please help me with this.
请帮我解决一下这个。
TypeError: list indices must be integers, not tuple. TypeError:列表索引必须是整数,而不是元组。
You rebind the name arr
to point to a Python list
in your fourth line, and so your question title doesn't quite fit: you're not slicing a 2d numpy array. 您将名称
arr
重新绑定为指向第四行中的Python list
,因此您的问题标题不太合适:您没有对2d numpy数组进行切片。 list
s can't be sliced the way that numpy arrays can. list
不能像numpy数组那样被切片。 Compare: 相比:
>>> arr= numpy.array([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
>>> arr
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> arr[1:2, 1]
array([5])
but 但
>>> arr.tolist()
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> arr.tolist()[1:2, 1]
Traceback (most recent call last):
File "<ipython-input-23-4a441cf2eaa9>", line 1, in <module>
arr.tolist()[1:2, 1]
TypeError: list indices must be integers, not tuple
arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
is a python list
,not a numpy array
. arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
是python list
,而不是numpy array
。
You reassign arr
with arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
to a list. 您将
arr
arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
重新分配给列表。
Make it a numpy array: 使它成为一个numpy数组:
In [37]: arr = numpy.array([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
In [38]: arr
Out[38]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [39]: (arr[1:2, 1])
Out[39]: array([5])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.