📊 数据基础 · Pandas 实战
🎓 机器学习赋能需求预测
🧱 核心数据结构
Series · DataFrame
📈 Series (一维标签数组)
- 定义:带索引的一维数组,可存储任意数据类型。
- 创建:
pd.Series([1,2,3], index=['a','b','c']) - 特点:类似字典 + NumPy 数组,支持向量化操作。
- 常用属性:
.values,.index,.dtype
import pandas as pd
s = pd.Series([85, 92, 78],
index=['春', '夏', '秋'])
print(s['夏']) # 92
🗂️ DataFrame (二维表格)
- 定义:行和列均有索引的二维数据结构。
- 创建:
pd.DataFrame(data, columns, index) - 核心:每一列是一个 Series,列类型可不同。
- 维度:
.shape返回 (行, 列)
df = pd.DataFrame({
'产品': ['A', 'B', 'C'],
'销量': [120, 95, 210]
})
print(df.shape) # (3, 2)
📂 数据读取 · CSV & Excel
read_csv / read_excel
📄 读取 CSV
pd.read_csv('sales.csv')- 常用参数:
sep,encoding='utf-8',header,index_col - 处理缺失:
na_values=['NA', '?']
df_csv = pd.read_csv(
'需求数据.csv',
encoding='gbk',
parse_dates=['日期']
)
df_csv.head(3)
📗 读取 Excel
pd.read_excel('data.xlsx', sheet_name='Sheet1')- 依赖库:
openpyxl或xlrd - 指定列类型:
dtype={'产品': str}
df_excel = pd.read_excel(
'预测基础.xlsx',
sheet_name=0,
usecols='A:C'
)
df_excel.info()
🔍 数据概览三剑客
head · info · describe
👀 .head()
- 默认显示前5行
df.head(10)查看前10行- 快速检查数据样式
df.head() 产品 销量 月份 0 A 120 1 1 B 95 1 2 C 210 2
📋 .info()
- 列名、非空计数、数据类型
- 内存使用量
- 发现缺失值
df.info() <class 'pandas.DataFrame'> RangeIndex: 3 entries Data columns: 3 产品 3 non-null object 销量 3 non-null int64 月份 2 non-null float64
📊 .describe()
- 数值列统计:count, mean, std, min, 25%, 50%, 75%, max
- 自动忽略非数值列
- 快速发现异常值
df.describe()
销量 月份
count 3.0 2.0
mean 141.7 1.5
std 60.1 0.7
min 95.0 1.0
max 210.0 2.0
| 统计量 | 销量 (int) | 月份 (float) | 库存 (float) |
|---|---|---|---|
| count | 1000.0 | 1000.0 | 998.0 |
| mean | 245.3 | 6.5 | 320.1 |
| std | 88.7 | 3.4 | 105.2 |
| min | 22.0 | 1.0 | 50.0 |
| 25% | 180.0 | 3.0 | 240.0 |
| 50% | 230.0 | 6.0 | 310.0 |
| 75% | 300.0 | 9.0 | 400.0 |
| max | 510.0 | 12.0 | 680.0 |
⚡ 组合使用:df.head(3) + df.info() + df.describe() 快速掌握数据全貌
⚙️ 数据基础架构流
从数据源到预测模型,Pandas 提供坚实的数据基础