user3923685
user3923685

Reputation: 11

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.

Upvotes: 1

Views: 145

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ]) is a python list,not a numpy array.

You reassign arr with arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ]) to a list.

Make it a numpy array:

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])

Upvotes: 1

DSM
DSM

Reputation: 352989

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. lists can't be sliced the way that numpy arrays can. 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

Upvotes: 1

Related Questions