Master the Numpy slicing operation method and easily process large-scale data. Specific code examples are required
Summary:
Use appropriate tools when processing large-scale data Very important. Numpy is a commonly used library in Python that provides high-performance numerical calculation tools. This article will introduce Numpy's slicing operation method, and use code examples to demonstrate how to easily operate and extract data when processing large-scale data.
import numpy as np a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
We can use colon: to specify the range of the slice. The sample code is as follows:
# 切片操作 b = a[2:6] # 从下标2到下标5的元素 print(b) # 输出:[2 3 4 5] c = a[:4] # 从开头到下标3的元素 print(c) # 输出:[0 1 2 3] d = a[6:] # 从下标6到末尾的元素 print(d) # 输出:[6 7 8 9] e = a[::3] # 每隔2个元素取一个 print(e) # 输出:[0 3 6 9]
b = np.array([[0, 1, 2], [3, 4, 5]])
We can specify the range of the slice by using commas. The sample code is as follows:
# 切片操作 c = b[0] # 提取第0行的元素 print(c) # 输出:[0 1 2] d = b[:, 1] # 提取所有行的第1列元素 print(d) # 输出:[1 4] e = b[:2, 1:] # 提取前两行以及第二列之后的元素 print(e) # 输出:[[1 2] # [4 5]]
c = np.array([[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]])
We can specify the range of the slice by increasing the number of commas. The sample code is as follows:
# 切片操作 d = c[0] # 提取第0个二维数组 print(d) # 输出:[[0 1 2] # [3 4 5] # [6 7 8]] e = c[:, 1, :] # 提取所有二维数组的第1行的元素 print(e) # 输出:[[ 3 4 5] # [12 13 14] # [21 22 23]] f = c[:, :, ::2] # 提取所有二维数组的每隔一个元素的列 print(f) # 输出:[[[ 0 2] # [ 3 5] # [ 6 8]] # [[ 9 11] # [12 14] # [15 17]] # [[18 20] # [21 23] # [24 26]]]
References:
Code example:
import numpy as np # 一维数组切片 a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) b = a[2:6] c = a[:4] d = a[6:] e = a[::3] # 二维数组切片 b = np.array([[0, 1, 2], [3, 4, 5]]) c = b[0] d = b[:, 1] e = b[:2, 1:] # 多维数组切片 c = np.array([[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) d = c[0] e = c[:, 1, :] f = c[:, :, ::2]
The above is the detailed content of Learn numpy slicing techniques to simplify large data processing. For more information, please follow other related articles on the PHP Chinese website!