机器学习基础入门——机器学习库介绍(NumPy、pandas、Matplotlib)

发布于:2025-02-25 ⋅ 阅读:(16) ⋅ 点赞:(0)

机器学习库介绍(NumPy、pandas、Matplotlib)

在 Python 机器学习的领域中,NumPy、pandas 和 Matplotlib 是三个不可或缺的基础库。它们分别在数值计算、数据处理与分析以及数据可视化方面发挥着关键作用,极大地提升了开发效率与数据洞察能力。接下来,我们将通过丰富的代码示例详细了解这三个库。

NumPy:高效的数值计算库

NumPy 提供了多维数组对象ndarray,以及大量用于数组操作的函数,使得数值计算变得高效且便捷。

创建数组

import numpy as np

# 创建一维数组

arr1 = np.array([1, 2, 3, 4])

print(arr1)

# 创建二维数组

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

print(arr2)

# 创建全零数组

zeros_arr = np.zeros((3, 4))

print(zeros_arr)

# 创建全一数组

ones_arr = np.ones((2, 3))

print(ones_arr)

# 创建指定范围的数组

range_arr = np.arange(1, 10, 2)

print(range_arr)

*示意不同方式创建的 NumPy 数组结构*

数组运算

a = np.array([1, 2, 3])

b = np.array([4, 5, 6])

# 数组相加

add_result = a + b

print(add_result)

# 数组相乘

mul_result = a * b

print(mul_result)

# 数组点积

dot_result = np.dot(a, b)

print(dot_result)

在这里插入图片描述

数组索引与切片

arr = np.array([10, 20, 30, 40, 50])

# 访问单个元素

print(arr[2])

# 切片操作

print(arr[1:4])

# 二维数组索引与切片

two_d_arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(two_d_arr[1, 2])

print(two_d_arr[:, 1])

在这里插入图片描述

pandas:强大的数据处理与分析库

pandas 的核心数据结构是Series(一维带标签数组)和DataFrame(二维表格型数据结构),提供了丰富的数据处理与分析方法。

创建数据结构

import pandas as pd

# 创建Series

data = [10, 20, 30, 40]

index = ['a', 'b', 'c', 'd']

series = pd.Series(data, index=index)

print(series)

# 创建DataFrame

data = {

   'Name': ['Alice', 'Bob', 'Charlie'],

   'Age': [25, 30, 35],

   'City': ['New York', 'London', 'Paris']

}

df = pd.DataFrame(data)

print(df)

在这里插入图片描述

展示 pandas 中 Series 和 DataFrame 的数据结构样式

数据读取与写入

# 从CSV文件读取数据

df = pd.read_csv('data.csv')

print(df.head())

# 将数据写入CSV文件

df.to_csv('new_data.csv', index=False)

数据清洗与处理

# 处理缺失值

df = pd.DataFrame({

   'A': [1, 2, None, 4],

   'B': [5, None, 7, 8]

})

df = df.dropna()  # 删除包含缺失值的行

print(df)

# 处理重复值

df = pd.DataFrame({

   'A': [1, 2, 2, 3],

   'B': [4, 5, 5, 6]

})

df = df.drop_duplicates()

print(df)

在这里插入图片描述

数据筛选与统计

df = pd.DataFrame({

   'Name': ['Alice', 'Bob', 'Charlie'],

   'Age': [25, 30, 35],

   'City': ['New York', 'London', 'Paris']

})

# 筛选年龄大于30的行

filtered_df = df[df['Age'] > 30]

print(filtered_df)

# 统计各列的描述性统计信息

stats = df.describe()

print(stats)

在这里插入图片描述

Matplotlib:数据可视化利器

Matplotlib 可以将数据以直观的图表形式展示出来,帮助我们更好地理解数据特征与趋势。

简单绘图

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 12, 15, 13]

plt.plot(x, y)

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

plt.title('Simple Line Plot')

plt.show()

在这里插入图片描述

Matplotlib 绘制的简单折线图示例

绘制多种图表

# 柱状图

labels = ['A', 'B', 'C', 'D']

values = [20, 35, 15, 30]

plt.bar(labels, values)

plt.show()

在这里插入图片描述

Matplotlib 绘制的柱状图示例

# 散点图

x = np.random.randn(100)

y = np.random.randn(100)

plt.scatter(x, y)

plt.show()

在这里插入图片描述

Matplotlib 绘制的散点图示例

# 饼图

sizes = [30, 20, 15, 35]

labels = ['Apple', 'Banana', 'Orange', 'Grapes']

plt.pie(sizes, labels=labels, autopct='%1.1f%%')

plt.show()

在这里插入图片描述

Matplotlib 绘制的饼图示例

通过上述对 NumPy、pandas 和 Matplotlib 库的详细介绍及代码示例,相信大家对这三个机器学习常用库有了更深入的理解。在实际项目中,灵活运用这些库能够大幅提升数据处理、分析与可视化的效率,为机器学习模型的构建与优化奠定坚实基础。