【Python自动化】 21 Pandas Excel 操作完整指南

发布于:2025-09-07 ⋅ 阅读:(27) ⋅ 点赞:(0)

一、Pandas 库介绍

什么是 Pandas?

Pandas 是 Python 中最强大的数据分析库,提供高效的 DataFrame 数据结构,专门用于处理表格化数据。

核心功能

  • 数据读取和写入(CSV、Excel、SQL 等)
  • 数据清洗和预处理
  • 数据转换和分析
  • 时间序列处理

二、安装与环境配置

基础安装

# 最小化安装
pip install pandas

# 包含 Excel 支持的安装(推荐)
pip install pandas openpyxl

# 使用 conda
conda install pandas
conda install openpyxl

验证安装

import pandas as pd
print(pd.__version__)  # 应显示版本号

三、基础 Excel 操作

正确的基本语法

import pandas as pd

# 创建 DataFrame - 正确语法
df = pd.DataFrame({
    "ID": [1, 2, 3],
    "Name": ["Tim", "Victor", "Nick"],
    "Age": [25, 30, 28]
})

# 写入 Excel 文件
df.to_excel("output.xlsx", index=False)
print("文件创建成功!")

四、常见错误案例及解决方案

错误案例 1: 拼写错误

# ❌ 错误代码
df = pd.DateFrame({"ID": [1, 2, 3]})  # DateFrame 拼写错误

# ✅ 正确代码
df = pd.DataFrame({"ID": [1, 2, 3]})   # DataFrame 正确拼写

错误信息:

AttributeError: module 'pandas' has no attribute 'DateFrame'. Did you mean: 'DataFrame'?

错误案例 2: 语法错误(方括号误用)

# ❌ 错误代码
df = pd.DataFrame[{"ID": [1, 2, 3]}]  # 使用了方括号

# ✅ 正确代码
df = pd.DataFrame({"ID": [1, 2, 3]})   # 使用圆括号

错误信息:

TypeError: type 'DataFrame' is not subscriptable

错误案例 3: 缺少依赖库

# ❌ 错误代码 - 缺少 openpyxl
df.to_excel("output.xlsx")  # 没有安装 openpyxl

# ✅ 解决方案
# 安装缺失的库
pip install openpyxl

# 或者指定引擎
df.to_excel("output.xlsx", engine='openpyxl')

错误信息:

ModuleNotFoundError: No module named 'openpyxl'

错误案例 4: 文件权限问题

# ❌ 错误代码 - 没有写入权限
df.to_excel("c:/system/output.xlsx")  # 系统目录无权限

# ✅ 解决方案
import os

# 尝试多个路径
paths = [
    "./output.xlsx",                    # 当前目录
    os.path.expanduser("~/output.xlsx") # 用户目录
]

for path in paths:
    try:
        df.to_excel(path, index=False)
        print(f"文件保存到: {path}")
        break
    except PermissionError:
        continue

错误信息:

PermissionError: [Errno 13] Permission denied

错误案例 5: 路径不存在

# ❌ 错误代码 - 目录不存在
df.to_excel("e:/nonexistent_folder/output.xlsx")

# ✅ 解决方案
import os

# 创建目录(如果不存在)
os.makedirs("e:/nonexistent_folder", exist_ok=True)
df.to_excel("e:/nonexistent_folder/output.xlsx")

五、完整的最佳实践代码

版本 1: 基础版本(带错误处理)

import pandas as pd
import os

def create_excel_safely():
    try:
        # 创建 DataFrame
        df = pd.DataFrame({
            "ID": [1, 2, 3],
            "Name": ["Tim", "Victor", "Nick"],
            "Department": ["IT", "HR", "Finance"],
            "Salary": [5000, 6000, 5500]
        })
        
        print("数据创建成功:")
        print(df)
        
        # 安全保存路径
        file_path = "./output.xlsx"
        
        # 写入 Excel
        df.to_excel(file_path, index=False, engine='openpyxl')
        
        # 验证文件
        if os.path.exists(file_path):
            print(f"✅ Excel 文件创建成功: {file_path}")
        else:
            print("❌ 文件创建失败")
            
    except Exception as e:
        print(f"❌ 发生错误: {e}")

if __name__ == "__main__":
    create_excel_safely()

版本 2: 高级版本(多路径尝试)

import pandas as pd
import os

def smart_excel_creator(data, filename="output.xlsx"):
    """
    智能创建 Excel 文件,自动尝试多个保存路径
    """
    # 定义可能的保存路径(按优先级排序)
    possible_paths = [
        "./" + filename,                    # 当前目录
        os.path.join(os.path.expanduser("~"), "Documents", filename),  # 文档目录
        os.path.join(os.path.expanduser("~"), filename),              # 用户目录
        f"c:/temp/{filename}",              # 临时目录
        f"e:/{filename}"                    # E盘根目录
    ]
    
    df = pd.DataFrame(data)
    
    for path in possible_paths:
        try:
            # 创建目录(如果不存在)
            os.makedirs(os.path.dirname(path), exist_ok=True)
            
            # 写入文件
            df.to_excel(path, index=False, engine='openpyxl')
            
            # 验证文件
            if os.path.exists(path):
                file_size = os.path.getsize(path)
                return {
                    "success": True,
                    "path": path,
                    "size": file_size,
                    "message": f"文件成功保存到: {path} ({file_size} 字节)"
                }
                
        except PermissionError:
            continue
        except Exception as e:
            continue
    
    return {
        "success": False,
        "message": "所有保存路径都失败,请检查权限和磁盘空间"
    }

# 使用示例
if __name__ == "__main__":
    data = {
        "ID": [1, 2, 3, 4, 5],
        "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"],
        "Age": [25, 30, 35, 28, 32],
        "City": ["北京", "上海", "广州", "深圳", "杭州"]
    }
    
    result = smart_excel_creator(data, "employees.xlsx")
    print(result["message"])
    
    if result["success"]:
        print("🎉 操作完成!")
    else:
        print("❌ 操作失败,请尝试手动指定路径")

六、环境检测脚本

安装验证脚本

# check_environment.py
import sys
import subprocess

def check_environment():
    """检查 Python 环境配置"""
    
    print("=" * 50)
    print("Python 环境检测")
    print("=" * 50)
    
    # 检查 Python 版本
    print(f"Python 版本: {sys.version}")
    
    # 检查必要库
    required_libs = ['pandas', 'openpyxl', 'numpy']
    missing_libs = []
    
    for lib in required_libs:
        try:
            __import__(lib)
            version = __import__(lib).__version__
            print(f"✅ {lib:10} | 已安装 | 版本: {version}")
        except ImportError:
            print(f"❌ {lib:10} | 未安装")
            missing_libs.append(lib)
    
    # 提示安装缺失的库
    if missing_libs:
        print(f"\n⚠️  缺少以下库: {', '.join(missing_libs)}")
        print("请运行以下命令安装:")
        print(f"pip install {' '.join(missing_libs)}")
        
        # 询问是否自动安装
        choice = input("\n是否自动安装缺失的库?(y/n): ")
        if choice.lower() == 'y':
            try:
                subprocess.check_call([sys.executable, "-m", "pip", "install"] + missing_libs)
                print("✅ 安装完成!")
            except subprocess.CalledProcessError:
                print("❌ 安装失败,请手动安装")
    
    print("=" * 50)

if __name__ == "__main__":
    check_environment()

七、Rust Polars 对比实现

Cargo.toml 配置

[package]
name = "excel_operations"
version = "0.1.0"
edition = "2021"

[dependencies]
polars = { version = "0.37", features = ["lazy", "xlsx", "temporal", "serde"] }

Rust 实现代码

use polars::prelude::*;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    // 创建 DataFrame
    let df = df! [
        "ID" => &[1, 2, 3],
        "Name" => &["Tim", "Victor", "Nick"],
        "Age" => &[25, 30, 28],
        "Department" => &["IT", "HR", "Finance"]
    ]?;

    println!("创建的 DataFrame:");
    println!("{:?}", df);

    // 写入 Excel 文件
    let mut file = std::fs::File::create("output_rust.xlsx")?;
    
    ExcelWriter::new(&mut file)
        .has_header(true)
        .finish(&mut df.clone())?;

    println!("✅ Excel 文件创建成功: output_rust.xlsx");

    Ok(())
}

八、总结对比

Pandas (Python) vs Polars (Rust)

特性 Pandas Polars
语法简洁性 ⭐⭐⭐⭐⭐ ⭐⭐⭐
性能 ⭐⭐⭐ ⭐⭐⭐⭐⭐
内存效率 ⭐⭐⭐ ⭐⭐⭐⭐⭐
错误处理 ⭐⭐⭐⭐ ⭐⭐⭐⭐
生态系统 ⭐⭐⭐⭐⭐ ⭐⭐⭐

推荐使用场景

  • Pandas: 快速原型开发、数据分析、机器学习预处理
  • Polars: 高性能数据处理、大规模数据、生产环境

最佳实践建议

  1. 总是使用错误处理 - 处理文件操作可能出现的异常
  2. 检查依赖库 - 确保安装了 openpyxl 等必要库
  3. 使用相对路径 - 避免权限问题
  4. 验证操作结果 - 检查文件是否真正创建成功
  5. 保持代码简洁 - 使用正确的语法和命名约定

通过掌握这些知识和技巧,您将能够高效地使用 Pandas 进行 Excel 文件操作,并避免常见的错误。


网站公告

今日签到

点亮在社区的每一天
去签到