Home > Back-end >  Python slice and delete function
Python slice and delete function

Time:11-25

I do not understand the slice function. I want to delete all columns from a certain number.

data = np.delete(data, slice(1344,-1), axis = 1)
print(data.shape)
print(data[0,1340:1345])
data = np.delete(data,1344, axis =1 )
print(data.shape)
print(data[0,1340:1345])

If I do so, data.shape somehow does not delete the last element and therefore I get a '0' there which I have to delete in an additional step.

(200000, 1345)
[435 432 426 438   0]
(200000, 1344)
[435 432 426 438]

If I decrease the index by 1,

data = np.delete(data, slice(1343,-1), axis = 1)
print(data.shape)
print(data[0,1340:1345])

I still get a '0' at the end, but the number before is deleted.

(200000, 1344)
[435 432 426   0]

How can I get in a single line an array with size of (200000, 1344) with no 0 at the end, but the real number?

CodePudding user response:

For a simple 1d array:

In [170]: x=np.arange(10)    
In [171]: x[slice(5,-1)]
Out[171]: array([5, 6, 7, 8])

The slice by itself is:

In [172]: slice(5,-1)
Out[172]: slice(5, -1, None)

which is the equivalent of:

In [173]: x[5:-1]
Out[173]: array([5, 6, 7, 8])

To get values starting from the end:

In [174]: x[slice(None,5,-1)]
Out[174]: array([9, 8, 7, 6])
In [176]: x[:5:-1]
Out[176]: array([9, 8, 7, 6])

Or deleting:

In [177]: np.delete(x,slice(None,5,-1))
Out[177]: array([0, 1, 2, 3, 4, 5])
  • Related