Unable to slice an array correctly

Viewed 86

I am having the following array

import numpy as np
T = np.array(([1,-1,0,0,0,0],
              [3,0,5,0,0,0],
              [0,-1,0,9,0,0],
              [0,0,0,0,-2,1],
              [3,1,0,0,2,0],
              [1,-2,1,0,2,2]))

I want to remove the first column and the last row of the array. So I should get:

T = [[-1 0 0 0 0],
    [0 5 0 0 0],
    [-1 0 9 0 0],
    [0 0 0 -2 1],
    [1 0 0 2 0]]

I wrote following line of code:

T = T[:len(T)-1][1:len(T[0])]

But I don't get the result I am expecting. The result I get is this:

[[ 3  0  5  0  0  0]
 [ 0 -1  0  9  0  0]
 [ 0  0  0  0 -2  1]
 [ 3  1  0  0  2  0]]

Can anyone tell me what I am doing wrong and also the correct way to slice the array?

2 Answers

If you slice an array like you did, what is returned is another array with the same number of dimensions. So your code is equivalent to:

T = T[:len(T)-1]
T = T[1:len(T[0])]

instead do:

T[:len(T)-1, 1:len(T[0])]

or just

T = T[:-1, 1:]

you are just removing the first list not the first element in all lists you can try some thing like this

T = [i[1:] for i in T]

by using this line you loop in all the nested lists and delete the first element from it

you can read more about list comprehension

Related