Pandas教程:数据分析与处理入门 – wiki基地

Pandas 教程:数据分析与处理入门

Pandas是Python中最流行的数据分析和处理库之一。它提供了一套强大的工具,用于高效地操作和分析结构化数据。无论你是数据科学家、分析师还是工程师,Pandas都是你不可或缺的利器。 本教程将带你入门Pandas,涵盖其核心概念、常用功能以及实际应用。

1. Pandas 简介:为何选择 Pandas?

Pandas 建立在 NumPy 之上,为表格型数据(如 SQL 表格和 Excel 表格)提供了灵活且高效的数据结构。 与 NumPy 专注于数值计算不同,Pandas 擅长处理各种数据类型(包括数值、字符串、日期等),并且提供了强大的数据清洗、转换、分析和可视化功能。

选择 Pandas 的理由:

  • 高效的数据结构: 提供了 Series(一维带标签数组)和 DataFrame(二维带标签表格)两种强大的数据结构。
  • 数据对齐: 自动地按标签对齐数据,方便处理不同数据源的数据。
  • 缺失数据处理: 优雅地处理缺失数据(NaN),并提供丰富的填充和删除方法。
  • 数据筛选和选择: 灵活地根据标签、位置或条件筛选和选择数据。
  • 数据转换和清洗: 提供了大量的数据转换和清洗函数,如类型转换、字符串处理、去重等。
  • 数据聚合和分组: 强大的 groupby 功能,可以进行数据聚合、透视表等操作。
  • 时间序列分析: 专门针对时间序列数据进行了优化,提供时间序列索引、重采样等功能。
  • 数据导入导出: 支持多种数据格式的导入导出,如 CSV、Excel、SQL 数据库等。
  • 可视化: 与 Matplotlib 和 Seaborn 等可视化库集成,方便进行数据可视化。

2. Pandas 的安装和导入

确保你已经安装了 Python。 然后,可以使用 pip 安装 Pandas:

bash
pip install pandas

安装完成后,就可以在 Python 代码中导入 Pandas 了:

python
import pandas as pd

通常约定使用 pd 作为 Pandas 的别名,方便代码编写。

3. Pandas 的核心数据结构:Series 和 DataFrame

3.1 Series:一维带标签数组

Series 类似于 NumPy 的一维数组,但它有一个重要的区别:Series 具有显式的标签索引。

  • 创建 Series:

    • 从列表创建:

      python
      data = [10, 20, 30, 40, 50]
      s = pd.Series(data)
      print(s)

      输出:

      0 10
      1 20
      2 30
      3 40
      4 50
      dtype: int64

    • 指定索引:

      python
      data = [10, 20, 30, 40, 50]
      index = ['a', 'b', 'c', 'd', 'e']
      s = pd.Series(data, index=index)
      print(s)

      输出:

      a 10
      b 20
      c 30
      d 40
      e 50
      dtype: int64

    • 从字典创建:

      python
      data = {'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50}
      s = pd.Series(data)
      print(s)

      输出:

      a 10
      b 20
      c 30
      d 40
      e 50
      dtype: int64

  • 访问 Series:

    • 通过索引标签:

      python
      print(s['a']) # 输出:10
      print(s[['a', 'c', 'e']]) # 输出一个包含 'a', 'c', 'e' 元素的 Series

    • 通过位置索引:

      python
      print(s[0]) # 输出:10
      print(s[0:3]) # 输出一个包含前三个元素的 Series

    • 条件筛选:

      python
      print(s[s > 30]) # 输出所有大于 30 的元素

  • Series 的常用属性:

    • index: 获取索引。
    • values: 获取值(NumPy 数组)。
    • dtype: 获取数据类型。
    • size: 获取元素个数。
    • name: 获取 Series 的名称。

3.2 DataFrame:二维带标签表格

DataFrame 是 Pandas 中最重要的数据结构。 它可以看作是由多个 Series 组成的字典,每个 Series 代表一列数据。

  • 创建 DataFrame:

    • 从字典创建:

      python
      data = {
      'name': ['Alice', 'Bob', 'Charlie', 'David'],
      'age': [25, 30, 28, 22],
      'city': ['New York', 'London', 'Paris', 'Tokyo']
      }
      df = pd.DataFrame(data)
      print(df)

      输出:

      name age city
      0 Alice 25 New York
      1 Bob 30 London
      2 Charlie 28 Paris
      3 David 22 Tokyo

    • 从列表的列表创建:

      python
      data = [
      ['Alice', 25, 'New York'],
      ['Bob', 30, 'London'],
      ['Charlie', 28, 'Paris'],
      ['David', 22, 'Tokyo']
      ]
      columns = ['name', 'age', 'city']
      df = pd.DataFrame(data, columns=columns)
      print(df)

      输出同上。

    • 从 NumPy 数组创建:

      python
      import numpy as np
      data = np.array([
      ['Alice', 25, 'New York'],
      ['Bob', 30, 'London'],
      ['Charlie', 28, 'Paris'],
      ['David', 22, 'Tokyo']
      ])
      columns = ['name', 'age', 'city']
      df = pd.DataFrame(data, columns=columns)
      print(df)

      输出同上。

  • 访问 DataFrame:

    • 访问列:

      python
      print(df['name']) # 输出 'name' 列,为一个 Series
      print(df[['name', 'age']]) # 输出 'name' 和 'age' 列,为一个新的 DataFrame

    • 访问行:

      • loc (基于标签):

        python
        print(df.loc[0]) # 输出第一行,索引标签为 0
        print(df.loc[[0, 2]]) # 输出索引标签为 0 和 2 的行

      • iloc (基于位置):

        python
        print(df.iloc[0]) # 输出第一行,位置索引为 0
        print(df.iloc[[0, 2]]) # 输出位置索引为 0 和 2 的行

    • 访问单个单元格:

      python
      print(df.loc[0, 'name']) # 输出第一行 'name' 列的值
      print(df.iloc[0, 0]) # 输出第一行第一列的值

    • 条件筛选:

      python
      print(df[df['age'] > 25]) # 输出 'age' 大于 25 的行
      print(df[(df['age'] > 25) & (df['city'] == 'London')]) # 输出 'age' 大于 25 且 'city' 为 'London' 的行

  • DataFrame 的常用属性:

    • index: 获取行索引。
    • columns: 获取列索引。
    • values: 获取值(NumPy 数组)。
    • dtypes: 获取每列的数据类型。
    • shape: 获取 DataFrame 的形状(行数,列数)。
    • size: 获取元素个数。
    • info(): 提供 DataFrame 的摘要信息,包括列名、数据类型、非空值数量等。
    • head(n): 显示 DataFrame 的前 n 行(默认为 5 行)。
    • tail(n): 显示 DataFrame 的后 n 行(默认为 5 行)。
    • describe(): 提供 DataFrame 的描述性统计信息,包括均值、标准差、最小值、最大值、四分位数等。

4. 数据导入和导出

Pandas 支持多种数据格式的导入和导出。

  • 从 CSV 文件导入:

    python
    df = pd.read_csv('data.csv')
    print(df.head())

    常用的 read_csv 参数:

    • sep: 分隔符(默认为逗号)。
    • header: 指定哪一行作为列名(默认为第一行)。
    • index_col: 指定哪一列作为索引。
    • encoding: 指定文件编码(例如 ‘utf-8’, ‘gbk’)。
  • 导出到 CSV 文件:

    python
    df.to_csv('output.csv', index=False) # index=False 表示不写入行索引

    常用的 to_csv 参数:

    • sep: 分隔符(默认为逗号)。
    • header: 是否写入列名(默认为 True)。
    • index: 是否写入行索引(默认为 True)。
    • encoding: 指定文件编码(例如 ‘utf-8’)。
  • 从 Excel 文件导入:

    python
    df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
    print(df.head())

    常用的 read_excel 参数:

    • sheet_name: 指定工作表名称或索引。
    • header: 指定哪一行作为列名(默认为第一行)。
    • index_col: 指定哪一列作为索引。
  • 导出到 Excel 文件:

    python
    df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)

    常用的 to_excel 参数:

    • sheet_name: 指定工作表名称。
    • header: 是否写入列名(默认为 True)。
    • index: 是否写入行索引(默认为 True)。
  • 从 SQL 数据库导入:

    python
    import sqlite3
    conn = sqlite3.connect('database.db')
    df = pd.read_sql_query("SELECT * FROM table_name", conn)
    conn.close()
    print(df.head())

  • 导出到 SQL 数据库:

    python
    import sqlite3
    conn = sqlite3.connect('database.db')
    df.to_sql('table_name', conn, if_exists='replace', index=False) #if_exists 控制如果表存在该如何处理 ('fail', 'replace', 'append')
    conn.close()

5. 数据清洗和转换

Pandas 提供了丰富的数据清洗和转换函数。

  • 处理缺失数据:

    • isnull() / notnull(): 检测缺失值。

      python
      print(df.isnull()) # 返回一个布尔 DataFrame,True 表示缺失值
      print(df.isnull().sum()) # 统计每列缺失值的数量

    • dropna(): 删除包含缺失值的行或列。

      python
      df.dropna() # 删除包含任何缺失值的行
      df.dropna(axis=1) # 删除包含任何缺失值的列
      df.dropna(thresh=3) # 删除至少包含 3 个非缺失值的行

    • fillna(): 填充缺失值。

      python
      df.fillna(0) # 用 0 填充所有缺失值
      df['age'].fillna(df['age'].mean(), inplace=True) # 用 'age' 列的均值填充该列的缺失值
      df.fillna(method='ffill') # 使用前一个有效值填充 (forward fill)
      df.fillna(method='bfill') # 使用后一个有效值填充 (backward fill)

  • 数据类型转换:

    • astype(): 转换数据类型。

      python
      df['age'] = df['age'].astype(int) # 将 'age' 列转换为整数类型
      df['city'] = df['city'].astype('category') # 将 'city' 列转换为类别类型

  • 字符串处理:

    • Pandas Series 对象可以使用 .str 属性访问字符串处理方法, 类似于 Python 的字符串方法。

      python
      df['name'] = df['name'].str.lower() # 将 'name' 列转换为小写
      df['city'] = df['city'].str.upper() # 将 'city' 列转换为大写
      df['name'] = df['name'].str.strip() # 去除 'name' 列的空格
      df['name'] = df['name'].str.replace('a', 'A') # 将 'name' 列中的 'a' 替换为 'A'
      df['city'] = df['city'].str.contains('New') # 检测 'city' 列中是否包含 'New',返回布尔 Series

  • 重复值处理:

    • duplicated(): 检测重复值。

      python
      print(df.duplicated()) # 返回一个布尔 Series,True 表示重复行

    • drop_duplicates(): 删除重复值。

      python
      df.drop_duplicates() # 删除所有重复行
      df.drop_duplicates(subset=['name', 'age']) # 删除 'name' 和 'age' 列重复的行

6. 数据聚合和分组

Pandas 提供了强大的 groupby 功能,可以进行数据聚合和分组。

  • groupby(): 分组数据。

    python
    grouped = df.groupby('city') # 按 'city' 列进行分组

  • 聚合函数:

    • count(): 计数。
    • sum(): 求和。
    • mean(): 均值。
    • median(): 中位数。
    • min(): 最小值。
    • max(): 最大值。
    • std(): 标准差。
    • var(): 方差。

    python
    print(grouped['age'].mean()) # 计算每个城市年龄的平均值
    print(grouped['age'].agg(['mean', 'median', 'std'])) # 计算每个城市年龄的均值、中位数和标准差

  • 自定义聚合函数:

    “`python
    def age_range(x):
    return x.max() – x.min()

    print(grouped[‘age’].agg(age_range)) # 计算每个城市年龄的范围
    “`

  • 透视表:

    • pivot_table(): 创建透视表。

      python
      pivot = pd.pivot_table(df, values='age', index='city', aggfunc='mean')
      print(pivot)

7. 时间序列分析

Pandas 对时间序列数据进行了优化。

  • 将字符串转换为日期时间类型:

    python
    df['date'] = pd.to_datetime(df['date'])

  • 设置时间序列索引:

    python
    df.set_index('date', inplace=True)

  • 时间序列索引:

    python
    print(df['2023-01']) # 获取 2023 年 1 月的数据
    print(df['2023-01-01':'2023-01-10']) # 获取 2023 年 1 月 1 日到 1 月 10 日的数据

  • 重采样:

    • resample(): 重采样数据。

      python
      df.resample('M').mean() # 按月重采样,计算平均值
      df.resample('D').ffill() # 按天重采样,使用前一个有效值填充

8. 总结与进阶学习

本教程介绍了 Pandas 的核心概念和常用功能,包括数据结构、数据导入导出、数据清洗转换、数据聚合分组和时间序列分析。 Pandas 功能强大,用法灵活。 掌握这些基础知识后,你就可以使用 Pandas 进行更复杂的数据分析和处理任务。

进阶学习建议:

  • 阅读 Pandas 官方文档: Pandas 官方文档是学习 Pandas 的最佳资源。
  • 练习实际项目: 通过实际项目来巩固所学知识,并探索 Pandas 的更多功能。
  • 学习高级 Pandas 特性: 例如多层索引、自定义函数、性能优化等。
  • 结合其他数据分析库: 例如 NumPy, Matplotlib, Seaborn, Scikit-learn 等,构建完整的数据分析流程。

希望这篇教程能够帮助你入门 Pandas,开启你的数据分析之旅!

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部