数据分析与数据科学
用数据驱动决策
数据科学技术栈
编程语言
├── Python (主流)
└── R (统计分析)
核心库
├── NumPy (数值计算)
├── Pandas (数据处理)
├── Matplotlib/Seaborn (可视化)
└── Scikit-learn (机器学习)
工具平台
├── Jupyter Notebook
├── Anaconda
└── Google Colab
NumPy数值计算
import numpy as np
# 创建数组
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2, 3], [4, 5, 6]])
# 常用操作
print(arr.shape) # (5,)
print(matrix.shape) # (2, 3)
print(arr.mean()) # 3.0
print(arr.std()) # 1.414
# 数组运算
arr2 = arr * 2 # [2, 4, 6, 8, 10]
arr3 = arr + arr # [2, 4, 6, 8, 10]
# 生成数组
zeros = np.zeros((3, 3))
ones = np.ones((2, 4))
range_arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
# 矩阵运算
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.dot(a, b)) # 矩阵乘法
print(a.T) # 转置
Pandas数据处理
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({
'name': ['张三', '李四', '王五', '赵六'],
'age': [25, 30, 35, 28],
'salary': [8000, 12000, 15000, 10000],
'department': ['技术', '销售', '技术', '市场']
})
# 基础查看
print(df.head()) # 前5行
print(df.info()) # 数据类型
print(df.describe()) # 统计描述
# 选择数据
df['name'] # 单列
df[['name', 'age']] # 多列
df.loc[0] # 按标签选行
df.iloc[0:2] # 按位置选行
df[df['age'] > 28] # 条件筛选
# 数据处理
df['bonus'] = df['salary'] * 0.1 # 新增列
df['age_group'] = df['age'].apply(lambda x: '青年' if x < 30 else '中年')
# 分组聚合
df.groupby('department')['salary'].mean()
df.groupby('department').agg({
'salary': ['mean', 'max'],
'age': 'mean'
})
# 排序
df.sort_values('salary', ascending=False)
# 缺失值处理
df.dropna() # 删除缺失
df.fillna(0) # 填充缺失
数据可视化
import matplotlib.pyplot as plt
import seaborn as sns
# 设置中文
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 基础图表
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# 折线图
axes[0, 0].plot([1, 2, 3, 4], [1, 4, 2, 3], marker='o')
axes[0, 0].set_title('折线图')
# 柱状图
axes[0, 1].bar(['A', 'B', 'C'], [3, 7, 5])
axes[0, 1].set_title('柱状图')
# 散点图
axes[1, 0].scatter([1, 2, 3, 4], [2, 4, 1, 3])
axes[1, 0].set_title('散点图')
# 饼图
axes[1, 1].pie([30, 40, 30], labels=['A', 'B', 'C'], autopct='%1.1f%%')
axes[1, 1].set_title('饼图')
plt.tight_layout()
plt.savefig('charts.png')
plt.show()
# Seaborn高级图表
plt.figure(figsize=(10, 6))
# 热力图
sns.heatmap(df.corr(), annot=True, cmap='coolwarm')
# 箱线图
sns.boxplot(x='department', y='salary', data=df)
# 分布图
sns.histplot(df['age'], kde=True)
数据分析流程
import pandas as pd
import matplotlib.pyplot as plt
# 1. 数据加载
df = pd.read_csv('sales_data.csv')
# 2. 数据清洗
df.drop_duplicates(inplace=True)
df.dropna(subset=['amount'], inplace=True)
df['date'] = pd.to_datetime(df['date'])
# 3. 数据探索
print("数据概览:")
print(df.describe())
print("\n各类别销售额:")
category_sales = df.groupby('category')['amount'].sum().sort_values(ascending=False)
print(category_sales)
# 4. 数据可视化
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 销售趋势
df.groupby(df['date'].dt.month)['amount'].sum().plot(ax=axes[0], marker='o')
axes[0].set_title('月度销售趋势')
axes[0].set_xlabel('月份')
axes[0].set_ylabel('销售额')
# 类别占比
category_sales.plot(kind='pie', ax=axes[1], autopct='%1.1f%%')
axes[1].set_title('各类别销售占比')
plt.tight_layout()
plt.savefig('analysis_report.png')
# 5. 导出报告
summary = pd.DataFrame({
'指标': ['总销售额', '平均订单', '订单数'],
'数值': [df['amount'].sum(), df['amount'].mean(), len(df)]
})
summary.to_excel('summary_report.xlsx', index=False)
学习路线图
第1阶段:基础 (2-3个月)
├── Python编程基础
├── NumPy数值计算
├── Pandas数据处理
└── 基础统计学
第2阶段:分析 (2-3个月)
├── 数据可视化
├── 探索性分析
├── SQL数据查询
└── 业务分析方法
第3阶段:进阶 (3-6个月)
├── 机器学习基础
├── 特征工程
├── A/B测试
└── 大数据工具
第4阶段:专业化 (持续)
├── 深度学习
├── 自然语言处理
├── 推荐系统
└── 数据工程
本章小结
- NumPy:高效数值计算
- Pandas:数据处理利器
- 可视化:Matplotlib/Seaborn
- 流程:加载→清洗→分析→可视化
→ 继续阅读:39-人工智能与机器学习