Explore common functions and usage of NumPy
NumPy is an open source Python scientific computing library that provides powerful multi-dimensional array objects and functions for processing these arrays. It is one of the most commonly used libraries in the field of data science and machine learning. With its efficient performance and flexibility, it has become a "powerful tool" for data analysts and scientists. This article will delve into NumPy's common functions and usage, and provide specific code examples.
First, let’s learn how to create a NumPy array. A NumPy array is an efficient multi-dimensional container object that can store data of the same type.
import numpy as np # 创建一维数组 a = np.array([1, 2, 3, 4, 5]) print(a) # 创建二维数组 b = np.array([[1, 2, 3], [4, 5, 6]]) print(b)
Output results:
[1 2 3 4 5] [[1 2 3] [4 5 6]]
NumPy provides many useful properties to describe the shape, size and data type of arrays.
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) # 数组形状 print(a.shape) # 数组维度 print(a.ndim) # 数组大小 print(a.size) # 数组数据类型 print(a.dtype)
Output results:
(2, 3) 2 6 int64
NumPy provides many powerful functions to operate arrays.
import numpy as np a = np.array([1, 2, 3, 4, 5]) # 数组求和 print(np.sum(a)) # 数组最小值和最大值 print(np.min(a)) print(np.max(a)) # 数组平均值和标准差 print(np.mean(a)) print(np.std(a)) # 数组排序 print(np.sort(a)) # 数组反转 print(np.flip(a))
Output results:
15 1 5 3.0 1.4142135623730951 [1 2 3 4 5] [5 4 3 2 1]
NumPy supports slicing and indexing operations on arrays to access specific parts of the array or element.
import numpy as np a = np.array([1, 2, 3, 4, 5]) # 数组切片 print(a[1:4]) # 数组索引 print(a[0]) print(a[-1])
Output results:
[2 3 4] 1 5
NumPy can perform basic mathematical and logical operations.
import numpy as np a = np.array([1, 2, 3, 4, 5]) b = np.array([5, 4, 3, 2, 1]) # 数组加法 print(np.add(a, b)) # 数组减法 print(np.subtract(a, b)) # 数组乘法 print(np.multiply(a, b)) # 数组除法 print(np.divide(a, b)) # 数组平方根 print(np.sqrt(a))
Output results:
[6 6 6 6 6] [-4 -2 0 2 4] [5 8 9 8 5] [0.2 0.5 1. 2. 5. ] [1. 1.41421356 1.73205081 2. 2.23606798]
The above are just examples of some common functions and usages in NumPy. NumPy also provides more functions and tools to process array data. Through learning and exploration, we can gradually become familiar with the powerful functions of NumPy and apply it flexibly in actual projects.
Through the introduction of this article, I believe that readers will have a deeper understanding of NumPy’s common functions and usage, and can flexibly apply them in actual projects. It is hoped that readers can better master the use skills of NumPy and improve the efficiency of data processing and analysis through continuous practice and learning.
The above is the detailed content of Learn some common functions and usage of numpy. For more information, please follow other related articles on the PHP Chinese website!