Python中有哪些常用的第三方库?它们的作用是什么?代码举例讲解

Python有很多常用和强大的第三方库,主要有:

1. Numpy:

  • 用于科学计算的库,提供高性能的矩阵运算和数值运算。
  • 可以处理大规模数组,实现向量.矩阵运算。
  • 用法:
import numpy as np

a = np.array([1, 2, 3]) 
b = np.array([4, 5, 6])

c = a + b   # [5 7 9]
d = np.dot(a, b)  # 22

2. Pandas:

  • 一个强大的分析结构化数据的工具集。
  • 提供了高性能.易用的数据结构和数据分析工具。
  • 用法:
import pandas as pd

s = pd.Series([1, 3, 6, np.nan, 44, 1])

df = pd.DataFrame({
   'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
}) 

df.sum()
df.mean()

3. Matplotlib:

  • 一个强大的画图库,用于生成各种硬拷贝格式和交互式可视化。
  • 可以绘制曲线图.散点图.条形图.直方图等。
  • 用法:
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 3, 1, 5, 4]

plt.plot(x, y)  
plt.xlabel('Time')  
plt.ylabel('Voltage')  
plt.show() 
  1. Scikit-learn:
  • 一个简单高效的数据挖掘和数据分析工具。
  • 实现了大量机器学习算法,如分类.回归.聚类.维度约减等。
  • 用法:
from sklearn.linear_model import LinearRegression

X = [[0, 1], [1, 1]]
y = [1, 3] 

model = LinearRegression()
model.fit(X, y)  

model.predict([[1, 2]])   #  [3]