Pandas读取数据:csv、excel、sql全攻略

目录

一、Pandas读取数据概览

二、CSV文件读取完全指南

[2.1 基础用法](#2.1 基础用法)

[2.2 常用参数详解](#2.2 常用参数详解)

[2.3 实战:处理不规范CSV](#2.3 实战:处理不规范CSV)

[2.4 大文件分块读取(内存不足的救星)](#2.4 大文件分块读取(内存不足的救星))

[2.5 常见编码问题解决](#2.5 常见编码问题解决)

三、Excel文件读取完全指南

[3.1 基础用法](#3.1 基础用法)

[3.2 读取多个Sheet](#3.2 读取多个Sheet)

[3.3 高级参数](#3.3 高级参数)

[3.4 实战:处理复杂Excel报表](#3.4 实战:处理复杂Excel报表)

[3.5 Excel性能优化](#3.5 Excel性能优化)

四、SQL数据库读取完全指南

[4.1 SQLite(轻量级,无需服务器)](#4.1 SQLite(轻量级,无需服务器))

[4.2 MySQL](#4.2 MySQL)

[4.3 PostgreSQL](#4.3 PostgreSQL)

[4.4 SQL Server](#4.4 SQL Server)

[4.5 实用技巧](#4.5 实用技巧)

[4.6 写入数据库(补充)](#4.6 写入数据库(补充))

五、其他常用数据读取方法

[5.1 JSON读取](#5.1 JSON读取)

[5.2 HTML表格读取](#5.2 HTML表格读取)

[5.3 剪贴板读取(最快捷)](#5.3 剪贴板读取(最快捷))

[5.4 读取压缩文件](#5.4 读取压缩文件)

六、实战案例:多数据源整合

七、常见错误与解决方案

八、性能优化技巧

九、总结

一、Pandas读取数据概览

Pandas支持几十种数据格式,最常用的包括:

|----------|---------------------|-------------|
| 数据源 | 核心函数 | 常用场景 |
| CSV/文本文件 | pd.read_csv() | 通用数据交换,日志文件 |
| Excel文件 | pd.read_excel() | 业务报表,财务数据 |
| SQL数据库 | pd.read_sql() | 数据库分析,数据仓库 |
| JSON | pd.read_json() | API接口数据 |
| HTML表格 | pd.read_html() | 网页数据抓取 |
| 剪贴板 | pd.read_clipboard() | 快速测试,临时数据 |

二、CSV文件读取完全指南

CSV(逗号分隔值)是最通用的数据格式。pd.read_csv() 功能极其强大,参数超过50个。

2.1 基础用法

python 复制代码
python
import pandas as pd

# 最简单的读取
df = pd.read_csv('data.csv')

# 查看前5行
print(df.head())

# 基本信息
print(df.info())

2.2 常用参数详解

python 复制代码
python
# 1. 指定分隔符(默认逗号,制表符用\t)
df = pd.read_csv('data.tsv', sep='\t')

# 2. 指定编码(解决中文乱码)
df = pd.read_csv('data.csv', encoding='utf-8')
# 或 encoding='gbk'(适用于Windows下Excel导出的CSV)

# 3. 无表头文件
df = pd.read_csv('data.csv', header=None, names=['col1', 'col2', 'col3'])

# 4. 指定某列为索引
df = pd.read_csv('data.csv', index_col=0)  # 第一列为索引

# 5. 只读取部分列
df = pd.read_csv('data.csv', usecols=['name', 'age', 'salary'])

# 6. 限制读取行数(适合大文件预览)
df = pd.read_csv('huge_file.csv', nrows=1000)

# 7. 跳过前几行或跳过特定行
df = pd.read_csv('data.csv', skiprows=2)  # 跳过前2行
df = pd.read_csv('data.csv', skiprows=[1, 3, 5])  # 跳过第1,3,5行

# 8. 处理缺失值标记
df = pd.read_csv('data.csv', na_values=['NA', 'Missing', '?', 'N/A'])

# 9. 指定数据类型(加快读取速度、节省内存)
dtypes = {'user_id': 'int32', 'age': 'int8', 'score': 'float32'}
df = pd.read_csv('data.csv', dtype=dtypes)

# 10. 日期列自动解析
df = pd.read_csv('data.csv', parse_dates=['date_column'])

2.3 实战:处理不规范CSV

python 复制代码
python
# 场景1:CSV中有注释行(以#开头)
df = pd.read_csv('data.csv', comment='#')

# 场景2:CSV中包含多个空行
df = pd.read_csv('data.csv', skip_blank_lines=True)

# 场景3:CSV值被引号包围,内部有逗号
df = pd.read_csv('data.csv', quotechar='"')

# 场景4:千位分隔符(如1,000,000)
df = pd.read_csv('data.csv', thousands=',')

# 场景5:布尔值映射
df = pd.read_csv('data.csv', true_values=['yes', 'True'], false_values=['no', 'False'])

2.4 大文件分块读取(内存不足的救星)

当文件太大无法一次性加载时,可以使用分块(chunk)读取:

python 复制代码
python
# 方法1:逐块处理
chunk_size = 10000
chunks = []
for chunk in pd.read_csv('huge_file.csv', chunksize=chunk_size):
    # 对每个chunk进行处理(如过滤、聚合)
    chunk = chunk[chunk['age'] > 18]
    chunks.append(chunk)

df = pd.concat(chunks, ignore_index=True)

# 方法2:只读取需要的行
result = pd.DataFrame()
for chunk in pd.read_csv('huge_file.csv', chunksize=50000):
    filtered = chunk[chunk['city'] == 'Beijing']
    result = pd.concat([result, filtered])

# 方法3:使用迭代器
reader = pd.read_csv('huge_file.csv', iterator=True)
first_chunk = reader.get_chunk(10000)
second_chunk = reader.get_chunk(10000)

2.5 常见编码问题解决

python 复制代码
python
# 检测文件编码(需要安装chardet)
import chardet

with open('data.csv', 'rb') as f:
    result = chardet.detect(f.read(10000))
    print(result['encoding'])  # 输出如 'utf-8' 或 'gb2312'

# 然后用检测到的编码读取
df = pd.read_csv('data.csv', encoding=result['encoding'])

# 常见编码速查
# utf-8-sig:带BOM的UTF-8(Excel保存的CSV常见)
# gbk:简体中文Windows默认
# ISO-8859-1:西欧语言

三、Excel文件读取完全指南

Excel是企业中最常见的格式,Pandas通过pd.read_excel()支持.xls和.xlsx。

3.1 基础用法

python 复制代码
python
# 需要安装openpyxl(xlsx)或xlrd(xls)
# pip install openpyxl xlrd

# 读取第一个sheet
df = pd.read_excel('data.xlsx')

# 读取指定sheet(按名称或索引)
df = pd.read_excel('data.xlsx', sheet_name='Sheet2')
df = pd.read_excel('data.xlsx', sheet_name=0)  # 第一个sheet

3.2 读取多个Sheet

python 复制代码
python
# 方法1:读取多个指定sheet
sheets = pd.read_excel('data.xlsx', sheet_name=['Sheet1', 'Sheet2'])
df1 = sheets['Sheet1']
df2 = sheets['Sheet2']

# 方法2:读取所有sheet
all_sheets = pd.read_excel('data.xlsx', sheet_name=None)  # 返回字典
for sheet_name, df in all_sheets.items():
    print(f"{sheet_name}: {df.shape}")

# 方法3:合并所有sheet
combined = pd.concat(all_sheets, ignore_index=True)

3.3 高级参数

python 复制代码
python
# 1. 指定列名行和数据的起始行
df = pd.read_excel('data.xlsx', header=1)  # 第2行为列名
df = pd.read_excel('data.xlsx', skiprows=2)  # 跳过前2行

# 2. 只读特定列(列名或位置)
df = pd.read_excel('data.xlsx', usecols='A,C:E')  # Excel列范围
df = pd.read_excel('data.xlsx', usecols=[0, 2, 3])  # 列索引

# 3. 读取合并单元格(填充值)
df = pd.read_excel('data.xlsx', header=0)
# 合并单元格会被填充为NaN,可以用ffill处理
df = df.fillna(method='ffill')

# 4. 指定数据类型(避免自动推断错误)
df = pd.read_excel('data.xlsx', dtype={'id': str, 'amount': float})

# 5. 日期解析
df = pd.read_excel('data.xlsx', parse_dates=['date_col'])

3.4 实战:处理复杂Excel报表

python 复制代码
python
# 场景1:Excel中有多个表头
df = pd.read_excel('report.xlsx', header=[0, 1])  # 前两行作为多层列名
print(df.columns)  # MultiIndex

# 场景2:跳过空行和无效信息
df = pd.read_excel('report.xlsx', skiprows=3, skipfooter=2)

# 场景3:读取指定的单元格区域
df = pd.read_excel('data.xlsx', usecols='B:D', skiprows=2, nrows=100)

# 场景4:处理没有表头的Excel
df = pd.read_excel('data.xlsx', header=None, names=['Col1', 'Col2', 'Col3'])

3.5 Excel性能优化

python 复制代码
python
# 大Excel文件只读需要的列
df = pd.read_excel('large.xlsx', usecols=['id', 'name', 'value'])

# 限制行数预览
df = pd.read_excel('large.xlsx', nrows=5000)

# 使用openpyxl引擎(对xlsx支持更好)
df = pd.read_excel('large.xlsx', engine='openpyxl')

四、SQL数据库读取完全指南

Pandas可以从各种SQL数据库读取数据,包括MySQL、PostgreSQL、SQLite、SQL Server等。

4.1 SQLite(轻量级,无需服务器)

python 复制代码
python
import sqlite3

# 连接数据库(如果不存在会自动创建)
conn = sqlite3.connect('database.db')

# 读取整个表
df = pd.read_sql('SELECT * FROM users', conn)

# 或者使用表名
df = pd.read_sql('users', conn)  # 等价于SELECT *

# 带条件的查询
df = pd.read_sql("SELECT name, age FROM users WHERE age > 25", conn)

# 关闭连接
conn.close()

4.2 MySQL

python 复制代码
python
# 需要安装 pymysql 或 mysql-connector-python
# pip install pymysql sqlalchemy

from sqlalchemy import create_engine

# 创建连接引擎
# 格式:mysql+pymysql://用户名:密码@主机:端口/数据库名
engine = create_engine('mysql+pymysql://root:password@localhost:3306/mydb')

# 读取数据
df = pd.read_sql('SELECT * FROM orders WHERE status = "completed"', engine)

# 使用参数化查询(防止SQL注入)
query = "SELECT * FROM products WHERE price > %s"
df = pd.read_sql(query, engine, params=[100])

# 分块读取大表
chunks = pd.read_sql('SELECT * FROM large_table', engine, chunksize=10000)
for chunk in chunks:
    process(chunk)

# 关闭引擎
engine.dispose()

4.3 PostgreSQL

python 复制代码
python
# 需要安装 psycopg2
# pip install psycopg2-binary sqlalchemy

from sqlalchemy import create_engine

engine = create_engine('postgresql://user:password@localhost:5432/mydb')
df = pd.read_sql('SELECT * FROM sales', engine)

4.4 SQL Server

python 复制代码
python
# 需要安装 pyodbc 或 pymssql
# pip install pyodbc

import pyodbc

conn = pyodbc.connect(
    'DRIVER={ODBC Driver 17 for SQL Server};'
    'SERVER=localhost;'
    'DATABASE=mydb;'
    'UID=user;'
    'PWD=password'
)
df = pd.read_sql('SELECT * FROM customers', conn)
conn.close()

4.5 实用技巧

python 复制代码
python
# 1. 读取大量数据时指定数据类型节省内存
dtypes = {'user_id': 'int32', 'amount': 'float32'}
df = pd.read_sql('SELECT * FROM transactions', engine, dtype=dtypes)

# 2. 将日期列解析为datetime
df = pd.read_sql('SELECT created_at, amount FROM orders', engine, parse_dates=['created_at'])

# 3. 使用索引列
df = pd.read_sql('SELECT id, name, age FROM users', engine, index_col='id')

# 4. 执行存储过程(以MySQL为例)
cursor = engine.raw_connection().cursor()
cursor.callproc('get_report', [param1, param2])
results = cursor.fetchall()
df = pd.DataFrame(results)

4.6 写入数据库(补充)

虽然重点是读取,但写入也是常见需求:

python 复制代码
python
# 将DataFrame写入SQL表
df.to_sql('table_name', engine, if_exists='replace', index=False)
# if_exists: 'fail', 'replace', 'append'

五、其他常用数据读取方法

5.1 JSON读取

python 复制代码
python
# 标准JSON文件
df = pd.read_json('data.json')

# JSON行格式(每行一个JSON对象)
df = pd.read_json('data.jsonl', lines=True)

# 从API接口读取
import requests
response = requests.get('https://api.example.com/data')
df = pd.DataFrame(response.json())

5.2 HTML表格读取

python 复制代码
python
# 读取网页中的所有表格
tables = pd.read_html('https://example.com/table.html')
df = tables[0]  # 第一个表格

# 指定匹配条件
tables = pd.read_html('page.html', match='销售数据')

5.3 剪贴板读取(最快捷)

python 复制代码
python
# 复制Excel中的几行数据,然后直接读取
df = pd.read_clipboard()
# 适合快速测试,不需要保存文件

5.4 读取压缩文件

python 复制代码
python
# 直接读取压缩包内的CSV
df = pd.read_csv('data.csv.gz', compression='gzip')
df = pd.read_csv('data.zip', compression='zip')

六、实战案例:多数据源整合

案例:销售数据分析

python 复制代码
python
import pandas as pd
import sqlite3

# 1. 读取CSV格式的用户信息
users = pd.read_csv('users.csv', encoding='utf-8', usecols=['user_id', 'name', 'city'])

# 2. 读取Excel格式的产品信息
products = pd.read_excel('products.xlsx', sheet_name='Sheet1', dtype={'product_id': str})

# 3. 从SQLite读取订单数据
conn = sqlite3.connect('sales.db')
orders = pd.read_sql("""
    SELECT order_id, user_id, product_id, quantity, order_date 
    FROM orders 
    WHERE order_date >= '2024-01-01'
""", conn)
conn.close()

# 4. 数据整合
df = orders.merge(users, on='user_id').merge(products, on='product_id')

# 5. 数据分析
summary = df.groupby('city').agg({
    'quantity': 'sum',
    'order_id': 'count'
}).rename(columns={'order_id': 'order_count'})

print(summary)

# 6. 保存结果到Excel
summary.to_excel('sales_summary.xlsx')

七、常见错误与解决方案

错误1:FileNotFoundError

python 复制代码
python
# 原因:文件路径错误
# 解决:使用绝对路径或检查相对路径
import os
print(os.getcwd())  # 查看当前工作目录
df = pd.read_csv(r'C:\data\file.csv')  # 原始字符串

错误2:UnicodeDecodeError(乱码)

python 复制代码
python
# 尝试不同编码
encodings = ['utf-8', 'gbk', 'gb2312', 'latin1', 'ISO-8859-1']
for enc in encodings:
    try:
        df = pd.read_csv('data.csv', encoding=enc)
        print(f"Success with {enc}")
        break
    except UnicodeDecodeError:
        continue

错误3:内存不足

python 复制代码
python
# 解决方案:
# 1. 分块读取
# 2. 指定数据类型(将float64转float32,object转category)
# 3. 只读取需要的列
df = pd.read_csv('large.csv', usecols=['col1', 'col2'], dtype={'col1': 'category'})

错误4:Excel引擎错误

python 复制代码
python
# 安装缺失的库
# pip install openpyxl  # 处理.xlsx
# pip install xlrd      # 处理.xls(旧版)
# 指定引擎
df = pd.read_excel('file.xlsx', engine='openpyxl')

错误5:SQL连接超时

python 复制代码
python
# 增加超时时间(SQLite)
conn = sqlite3.connect('database.db', timeout=30)
# MySQL可在连接字符串中设置
engine = create_engine('mysql+pymysql://...?connect_timeout=60')

八、性能优化技巧

|--------------|-----------------------------|-----------|
| 技巧 | 代码示例 | 效果 |
| 指定数据类型 | dtype={'id': 'int32'} | 内存减少50%+ |
| 只读必要列 | usecols=['a','b'] | 速度提升2-10倍 |
| 分块读取 | chunksize=10000 | 避免内存溢出 |
| 使用category类型 | dtype={'gender':'category'} | 内存减少90% |
| 索引列 | index_col=0 | 加快查询 |
| 关闭引擎 | engine.dispose() | 释放连接 |

性能对比示例

python 复制代码
python
import time

# 不优化
start = time.time()
df = pd.read_csv('large.csv')
print(f"Default: {time.time()-start:.2f}s, memory: {df.memory_usage().sum()/1e6:.1f}MB")

# 优化后
start = time.time()
dtypes = {'id': 'int32', 'value': 'float32', 'category_col': 'category'}
df = pd.read_csv('large.csv', usecols=['id', 'value', 'category_col'], dtype=dtypes)
print(f"Optimized: {time.time()-start:.2f}s, memory: {df.memory_usage().sum()/1e6:.1f}MB")

九、总结

核心函数速查

python 复制代码
python
# CSV
pd.read_csv(filepath, sep=',', encoding='utf-8', nrows=None, chunksize=None)

# Excel
pd.read_excel(filepath, sheet_name=0, header=0, usecols=None, dtype=None)

# SQL
pd.read_sql(sql, con, index_col=None, parse_dates=None, chunksize=None)

# 其他
pd.read_json()      # JSON
pd.read_html()      # HTML表格
pd.read_clipboard() # 剪贴板
pd.read_parquet()   # Parquet(列式存储,推荐大文件)

数据读取最佳实践

  1. 预览数据:先用 nrows=5 快速查看结构

  2. 指定类型:手动指定dtype可大幅节省内存

  3. 处理缺失值:使用 na_values 统一标记

  4. 日期列:用 parse_dates 提前解析

  5. 大文件:分块读取或使用Parquet格式

如果这篇文章对您有帮助,欢迎点赞、收藏、关注哦!

相关推荐
飞Link2 小时前
LangGraph SDK 全量技术手册:分布式 Agent 集群的远程调用与编排引擎
开发语言·分布式·python·数据挖掘
迷藏4942 小时前
**基于Python与OpenCV的光场显示图像处理技术实践**在现代显示技术发展中,**光场显示(Light
java·图像处理·python·opencv
枫叶林FYL2 小时前
【Python高级工程与架构实战】项目六:RAG知识库问答系统(企业文档智能)
python·深度学习·机器学习
witAI2 小时前
gpt写小说工具2025推荐,助力高效创作小说
人工智能·python·gpt
Roselind_Yi2 小时前
【开源仓库系列学习分享】MemPalace 仓库(超级记忆管家)全流程部署!(专业版)
人工智能·经验分享·笔记·python·数据挖掘·github·知识图谱
Flying pigs~~2 小时前
检索增强生成RAG项目tools_04:flask➕fastapi➕高并发
数据库·python·flask·大模型·fastapi·异步
JACK的服务器笔记2 小时前
《服务器测试百日学习计划——Day19:PCIe自动检测脚本,用Python把lspci设备清点标准化》
服务器·python·学习
YJlio2 小时前
Sysinternals实战教程专栏介绍:这不是一本到此为止的书,而是一套看穿 Windows 的排障方法
windows·python·电脑·outlook·windows部署·eixv3·pe装机
好运的阿财2 小时前
OpenClaw工具拆解之 sessions_list+sessions_history
人工智能·python·程序人生·ai·ai编程·openclaw