numpy slicing
时间: 2023-10-22 19:03:37 浏览: 65
NumPy slicing refers to the process of selecting a subset of elements from an array based on their indices, using the `[]` indexing operator. Slicing in NumPy works in a similar way to Python lists, but with some additional features.
The basic syntax for slicing a NumPy array is as follows:
```
array[start:stop:step]
```
where `start` is the index of the first element to include, `stop` is the index of the first element to exclude, and `step` is the spacing between the selected elements.
Here are some examples of NumPy slicing:
```python
import numpy as np
# Create a 1D array from 0 to 9
arr = np.arange(10)
# Select elements 2 through 5 (exclusive)
print(arr[2:5]) # Output: [2 3 4]
# Select every other element starting from the first
print(arr[::2]) # Output: [0 2 4 6 8]
# Reverse the order of the array
print(arr[::-1]) # Output: [9 8 7 6 5 4 3 2 1 0]
# Create a 2D array
arr2d = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
# Select the first two rows and the first two columns
print(arr2d[:2, :2]) # Output: [[0 1] [3 4]]
# Select the last row and the last two columns
print(arr2d[-1:, -2:]) # Output: [[7 8]]
```
In addition to these basic slicing operations, NumPy also supports advanced indexing, which allows you to select elements based on Boolean masks or integer arrays.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)