📦 库存预测 · 数据基础

Pandas 实战 🧩 第3节

📖 数据基础操作 读取CSV/Excel · 数据预览 · 类型转换 · 为库存预测模型清洗数据

📂 读取 CSV / Excel

📄 CSV 读取

  • pd.read_csv() 最常用
  • 参数 encoding='utf-8' 处理中文
  • dtype 指定列类型
  • parse_dates 解析日期
import pandas as pd

df_csv = pd.read_csv(
    'inventory_data.csv',
    encoding='utf-8',
    parse_dates=['日期']
)
print(df_csv.shape)

📗 Excel 读取

  • pd.read_excel() 需要 openpyxl
  • 参数 sheet_name 指定工作表
  • header 指定列名行
  • 支持多sheet读取
df_excel = pd.read_excel(
    '库存数据.xlsx',
    sheet_name='Sheet1',
    engine='openpyxl'
)
df_excel.head(3)
🔍 数据预览三剑客

👁️ head() & info()

  • df.head(10) 查看前10行
  • df.info() 列名、非空数、数据类型
  • 快速发现缺失值 & 类型异常
print(df.head(8))
print(df.info())
列名非空数类型
商品ID1000int64
日期1000datetime64
库存量998float64
销量1000int64

📊 describe() 统计摘要

  • 数值列自动统计:count, mean, std, min, 25%, 50%, 75%, max
  • 识别异常极值 & 分布
print(df.describe())
min 25% 50% mean 75% max
⚙️ 数据类型转换

🔄 常用转换方法

  • astype() 强制转换
  • pd.to_datetime() 日期转换
  • pd.to_numeric() 数字转换
  • 处理错误:errors='coerce'
# 日期转换
df['日期'] = pd.to_datetime(
    df['日期'], errors='coerce'
)

# 库存量转为浮点
df['库存量'] = pd.to_numeric(
    df['库存量'], errors='coerce'
)

# 商品ID 转为字符串
df['商品ID'] = df['商品ID'].astype(str)

🧩 类型检查 & 内存优化

  • df.dtypes 查看所有列类型
  • category 类型节省内存
  • int8/16/32 按需使用
print(df.dtypes)

# 转为category
df['商品类别'] = df['商品类别'].astype('category')

# 内存占用
print(df.memory_usage(deep=True))
🧭 数据基础操作流程 · 架构
📂 读取 CSV / Excel 🔍 预览 head/info/describe ⚙️ 转换 astype / to_datetime ✅ 原始数据 快速洞察 清洗 & 标准化 就绪

📋 常见数据类型转换表

原始类型目标类型方法说明
object (日期字符串)datetime64pd.to_datetime()errors='coerce' 容错
object (数字)float64 / int64pd.to_numeric()downcast 优化
int64 (类别)categoryastype('category')节省内存
float64 (整数)int64astype('Int64')可处理缺失值