NumPy Array Snijden

Knip de array

Het knippen in Python betekent het verplaatsen van elementen van een gegeven index naar een andere gegeven index.

We passeren een snee in plaats van indices, zoals hieronder te zien is:[begin:einde].

We kunnen ook een stapgrootte definiëren, zoals hieronder te zien is:[begin:einde:stap].

Als we niets overhandigen beginwordt als 0 beschouwd.

Als we niets overhandigen eindewordt als de lengte van de array binnen die dimensie beschouwd.

Als we niets overhandigen stapwordt als 1 beschouwd.

Example

Knip de elementen van index 1 tot index 5 af van de onderstaande array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])

Run Example

Note:Het resultaat omvat de beginindex, maar niet de eindindex.

Example

Cut the elements from index 4 to the end of the array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])

Run Example

Example

Cut the elements from the beginning to index 4 (not including):

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[:4])

Run Example

Negative Cutting

Use the minus operator to reference the index from the end:

Example

Cut the array from index 3 from the end to index 1 from the end:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])

Run Example

STEP

Please use the step value to determine the cutting step length:

Example

Return the elements at intervals from index 1 to index 5:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])

Run Example

Example

Return the elements at intervals in the array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[::2])

Run Example

Cut 2-D Array

Example

Start from the second element, slice the elements from index 1 to index 4 (not including):

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])

Run Example

Note:Remember that the index of the second element is 1.

Example

Return index 2 from two elements:

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])

Run Example

Example

Cut the index from two elements 1 to index 4 (not including), which will return a 2-D array:

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])

Run Example