简体   繁体   English

Python 切片和删除 function

[英]Python slice and delete function

I do not understand the slice function. I want to delete all columns from a certain number.我不明白切片 function。我想删除某个数字的所有列。

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.如果我这样做,data.shape 不会以某种方式删除最后一个元素,因此我在那里得到一个“0”,我必须在一个额外的步骤中删除它。

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

If I decrease the index by 1,如果我将索引减少 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.最后我仍然得到一个“0”,但之前的数字被删除了。

(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?我怎样才能在一行中得到一个大小为 (200000, 1344) 的数组,末尾没有 0,而是实数?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM