欢迎访问宙启技术站
智能推送

常用Python编程函数库及其使用方法

发布时间:2023-06-09 06:24:03

Python作为一种高效的编程语言,经过多年的发展,已经有了非常丰富的函数库,可以让你在编程时更加高效和方便。在本文中,我将介绍一些常用的Python函数库及其使用方法。

## NumPy

NumPy是一个用于科学计算的Python函数库,它提供了高性能的多维数组对象和计算工具。它的核心是ndarray,这是一个具有矢量算术运算和复杂广播能力的快速且节省空间的数组。

使用方法:

1. 导入NumPy

   import numpy as np
   

2.创建ndarray

   a = np.array([1, 2, 3])      # 1D array 
   b = np.array([[1, 2], [3, 4]])  # 2D array
   c = np.zeros((2, 3))         # 2x3 array filled with 0
   d = np.ones((2, 3))          # 2x3 array filled with 1
   e = np.random.rand(2, 3)     # 2x3 array with random values
   

3. 运算

   f = a + 2  # element-wise addition
   g = a.dot(b) # matrix multiplication
   h = np.sin(a) # apply sin function to each element
   i = np.sum(b, axis=0) # column-wise sum
   j = np.std(e) # standard deviation of all values in e
   

## Pandas

Pandas是一个强大且灵活的数据分析函数库,它提供了大量的数据结构和数据分析工具,如Series和DataFrame。

使用方法:

1. 导入Pandas

   import pandas as pd
   

2. 创建DataFrame

   df = pd.DataFrame(
         {
             "Name": ["Alice", "Bob", "Charlie", "Dave"],
             "Age": [25, 30, 35, 40],
             "Salary": [40000, 50000, 60000, 70000],
         }
     )
   

3. 数据操作

   df.head() #显示前5行
   df.tail() #显示后5行
   df.columns #列名
   df.describe() #数值型数据统计指标
   df[df['Age'] > 30] #选择Age > 30的行
   df[['Name', 'Salary']] #选择Name和Salary列
   df.groupby('Age').mean() #按照Age分组,并计算每组的平均值
   

## Matplotlib

Matplotlib是一个流行的Python数据可视化函数库。它可以创建各种类型的静态图形,并提供了一些交互式元素。它可以用于绘制折线图、散点图、直方图、饼图、热力图等等。

使用方法:

1. 导入Matplotlib

   import matplotlib.pyplot as plt
   

2. 绘制折线图

   x = [1, 2, 3, 4, 5]
   y = [2, 4, 1, 5, 3]
   plt.plot(x, y, label="line")
   plt.title("Line plot")
   plt.xlabel("X axis")
   plt.ylabel("Y axis")
   plt.legend()
   plt.show()
   

![image-20210629093523658](https://i.loli.net/2021/06/29/TdGkbz3O6UEcv4q.png)

3. 绘制散点图

   x = [1, 2, 3, 4, 5]
   y = [2, 4, 1, 5, 3]
   plt.scatter(x, y, label="scatter")
   plt.title("Scatter plot")
   plt.xlabel("X axis")
   plt.ylabel("Y axis")
   plt.legend()
   plt.show()
   

![image-20210629093629122](https://i.loli.net/2021/06/29/rzilD8fc1w2BvnM.png)

4. 绘制直方图

   x = [1, 2, 3, 4, 5]
   plt.hist(x, bins=10, label="histogram")
   plt.title("Histogram")
   plt.xlabel("X axis")
   plt.ylabel("Frequency")
   plt.legend()
   plt.show()
   

![image-20210629093721573](https://i.loli.net/2021/06/29/MKdgwIW4jRATynq.png)

## Scikit-learn

Scikit-learn是一个流行的Python机器学习函数库,它提供了许多流行的机器学习模型和数据预处理工具。它可以用于分类、聚类、回归、降维等任务。

使用方法:

1. 导入Scikit-learn

   from sklearn import datasets
   from sklearn.model_selection import train_test_split
   from sklearn.neighbors import KNeighborsClassifier
   from sklearn.metrics import accuracy_score
   

2. 加载数据

   iris = datasets.load_iris()
   X = iris.data
   y = iris.target
   

3. 划分训练集和测试集

   X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
   

4. 训练模型

   knn = KNeighborsClassifier(n_neighbors=3)
   knn.fit(X_train, y_train)
   

5. 预测

   y_pred = knn.predict(X_test)
   

6. 评估

   acc = accuracy_score(y_test, y_pred)
   print("Accuracy:", acc)
   

## TensorFlow

TensorFlow是Google推出的一款深度学习框架。它提供了丰富的工具和API,让你可以轻松地构建和训练深度学习模型。TensorFlow可以用于图像分类、自然语言处理、语音识别等任务。

使用方法:

1. 导入TensorFlow

   import tensorflow as tf
   

2. 定义模型

   model = tf.keras.models.Sequential([
         tf.keras.layers.Dense(64, activation=tf.nn.relu, input_shape=(784,)),
         tf.keras.layers.Dense(10, activation=tf.nn.softmax)
     ])
   

3. 编译模型

   model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
   

4. 训练模型

   model.fit(train_images, train_labels, epochs=5)
   

5. 评估模型

   test_loss, test_acc = model.evaluate(test_images, test_labels)
   print('Test accuracy:', test_acc)
   

以上是介绍了一些常用的Python函数库及其使用方法,希望对你学习Python编程有所帮助。当然,这只是其中的一小部分,Python的函数库非常多且丰富,还有很多其他的函数库可以使用,可以根据不同的需求去选择相应的函数库来使用。