第一阶段学习总结:Python 数据工程师必备技能速查表
·
第一阶段学习总结:Python 数据工程师必备技能速查表
一句话概括:26天从零到一,掌握 Python + SQL + Pandas + NumPy + 可视化,完成第一个数据项目。
先看问题
假设老板让你做一个数据分析任务:
- 读取数据:从 CSV 文件读取销售数据
- 数据清洗:处理缺失值、重复值
- 数据分析:计算各产品销售额、找出销量最高的日期
- 数据存储:把结果存入数据库
- 可视化:生成销售额趋势图
- 版本管理:代码上传 GitHub
你需要用到哪些技能?本文帮你整理成速查表!
一、Python 基础数据结构
1. String(字符串)
# 常用方法
s = "Hello World"
s.upper() # 'HELLO WORLD' - 转大写
s.lower() # 'hello world' - 转小写
s.strip() # 去除首尾空格
s.split(' ') # ['Hello', 'World'] - 分割
s.replace('H', 'h') # 'hello World' - 替换
s.startswith('He') # True - 是否以某字符串开头
s.endswith('ld') # True - 是否以某字符串结尾
' '.join(['a', 'b']) # 'a b' - 连接列表
s.find('World') # 6 - 查找位置
s.count('l') # 3 - 统计出现次数
len(s) # 11 - 长度
s[0:5] # 'Hello' - 切片
f"值: {s}" # f-string 格式化
小 Demo:解析邮箱用户名
email = "zhangsan@example.com"
username = email.split('@')[0]
domain = email.split('@')[1]
print(f"用户名: {username}, 域名: {domain}")
# 输出: 用户名: zhangsan, 域名: example.com
2. List(列表)
# 常用方法
lst = [1, 2, 3, 4, 5]
lst.append(6) # [1,2,3,4,5,6] - 末尾添加
lst.insert(0, 0) # [0,1,2,3,4,5,6] - 指定位置插入
lst.extend([7, 8]) # 添加多个元素
lst.remove(3) # 删除值为3的元素
lst.pop() # 删除并返回最后一个元素
lst.pop(0) # 删除并返回索引0的元素
lst.index(4) # 3 - 查找元素索引
lst.count(2) # 统计出现次数
lst.sort() # 排序(原地修改)
lst.reverse() # 反转(原地修改)
len(lst) # 长度
lst[0:3] # 切片
lst[-1] # 最后一个元素
小 Demo:找出列表中的最大值和最小值
scores = [85, 92, 78, 90, 88]
print(f"最高分: {max(scores)}")
print(f"最低分: {min(scores)}")
print(f"平均分: {sum(scores) / len(scores):.2f}")
# 输出: 最高分: 92, 最低分: 78, 平均分: 86.60
3. Tuple(元组)
# 元组不可修改,但可以解包
t = (1, 2, 3)
a, b, c = t # 解包: a=1, b=2, c=3
t[0] # 1 - 索引访问
t.count(2) # 统计出现次数
t.index(3) # 查找索引
len(t) # 长度
小 Demo:函数返回多个值
def get_min_max(numbers):
return min(numbers), max(numbers)
min_val, max_val = get_min_max([1, 5, 3, 9, 2])
print(f"最小值: {min_val}, 最大值: {max_val}")
# 输出: 最小值: 1, 最大值: 9
4. Dictionary(字典)
# 常用方法
d = {'name': '张三', 'age': 25}
d['city'] = '北京' # 添加/修改
d.get('name') # '张三' - 获取值
d.get('salary', 0) # 0 - 获取值,不存在返回默认值
d.keys() # dict_keys(['name', 'age', 'city'])
d.values() # dict_values(['张三', 25, '北京'])
d.items() # 返回键值对
d.pop('age') # 删除并返回值
d.update({'age': 26}) # 批量更新
'name' in d # True - 检查键是否存在
d.setdefault('gender', '男') # 不存在则设置默认值
小 Demo:统计单词出现次数
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count = {}
for word in words:
count[word] = count.get(word, 0) + 1
print(count)
# 输出: {'apple': 3, 'banana': 2, 'orange': 1}
二、Pandas 常用方法
import pandas as pd
# 读取数据
df = pd.read_csv('data.csv')
df = pd.read_excel('data.xlsx')
df = pd.read_sql('SELECT * FROM table', engine)
# 查看数据
df.head(5) # 前5行
df.tail(5) # 后5行
df.shape # (行数, 列数)
df.info() # 数据类型信息
df.describe() # 统计描述
df.columns # 列名
df.dtypes # 数据类型
# 选择数据
df['col'] # 选择单列
df[['col1', 'col2']] # 选择多列
df.loc[0] # 按标签选择行
df.iloc[0] # 按位置选择行
df.loc[df['age'] > 18] # 条件筛选
# 数据清洗
df.dropna() # 删除缺失值
df.fillna(0) # 填充缺失值
df.drop_duplicates() # 删除重复值
df.rename(columns={'old': 'new'}) # 重命名列
df.astype({'col': 'int'}) # 类型转换
# 分组聚合
df.groupby('col').sum()
df.groupby('col').agg({'col1': 'mean', 'col2': 'sum'})
df.pivot_table(values='val', index='row', columns='col')
# 合并
pd.merge(df1, df2, on='key') # 类似 SQL JOIN
pd.concat([df1, df2]) # 拼接
# 导出
df.to_csv('output.csv', index=False)
df.to_sql('table', engine, if_exists='replace')
小 Demo:销售数据分析
import pandas as pd
# 创建数据
data = {
'product': ['A', 'B', 'A', 'C', 'B', 'A'],
'quantity': [10, 20, 15, 30, 25, 20],
'price': [100, 200, 100, 300, 200, 100]
}
df = pd.DataFrame(data)
# 计算销售额
df['sales'] = df['quantity'] * df['price']
# 各产品总销售额
result = df.groupby('product')['sales'].sum()
print(result)
# 输出:
# A 4500
# B 9000
# C 9000
三、NumPy 常用方法
import numpy as np
# 创建数组
np.array([1, 2, 3])
np.zeros((3, 3)) # 全0数组
np.ones((3, 3)) # 全1数组
np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
np.random.rand(3, 3) # 随机数组
# 数组属性
arr.shape # 形状
arr.ndim # 维度
arr.size # 元素总数
arr.dtype # 数据类型
# 数组运算
arr + 10 # 每个元素加10
arr * 2 # 每个元素乘2
arr1 @ arr2 # 矩阵乘法
arr.T # 转置
# 统计函数
np.sum(arr)
np.mean(arr)
np.std(arr)
np.max(arr)
np.min(arr)
np.argmax(arr) # 最大值索引
np.argsort(arr) # 排序后的索引
# 形状操作
arr.reshape(3, 4) # 改变形状
arr.flatten() # 展平为一维
np.concatenate([a, b]) # 拼接
小 Demo:计算学生成绩标准分
import numpy as np
scores = np.array([85, 92, 78, 90, 88])
mean = np.mean(scores)
std = np.std(scores)
# 标准分 = (原始分 - 平均分) / 标准差
z_scores = (scores - mean) / std
print(f"平均分: {mean:.2f}, 标准差: {std:.2f}")
print(f"标准分: {z_scores}")
四、SQLAlchemy 常用方法
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 连接数据库
engine = create_engine('postgresql://user:pass@host:port/db')
# 定义模型
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
# 创建表
Base.metadata.create_all(engine)
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# CRUD 操作
# Create
user = User(name='张三')
session.add(user)
session.commit()
# Read
users = session.query(User).all()
user = session.query(User).filter_by(name='张三').first()
# Update
user.name = '李四'
session.commit()
# Delete
session.delete(user)
session.commit()
# 关闭会话
session.close()
小 Demo:用户管理系统
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///users.db')
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
age = Column(Integer)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# 添加用户
session.add(User(name='张三', age=25))
session.add(User(name='李四', age=30))
session.commit()
# 查询所有用户
for user in session.query(User).all():
print(f"{user.name}: {user.age}岁")
session.close()
五、Matplotlib 常用方法
import matplotlib.pyplot as plt
# 基础设置
plt.figure(figsize=(10, 6)) # 设置画布大小
plt.title('标题')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.legend() # 显示图例
plt.grid(True) # 显示网格
# 常用图表
plt.plot(x, y) # 折线图
plt.bar(x, y) # 柱状图
plt.scatter(x, y) # 散点图
plt.hist(data, bins=10) # 直方图
plt.pie(data, labels=labels) # 饼图
# 子图
fig, axes = plt.subplots(2, 2) # 2x2 子图
axes[0, 0].plot(x, y)
# 保存
plt.savefig('chart.png', dpi=150)
plt.show()
小 Demo:销售趋势图
import matplotlib.pyplot as plt
months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales = [100, 120, 90, 150, 180, 200]
plt.figure(figsize=(10, 6))
plt.plot(months, sales, marker='o', linewidth=2)
plt.title('月度销售趋势')
plt.xlabel('月份')
plt.ylabel('销售额(万元)')
plt.grid(True)
plt.savefig('sales_trend.png', dpi=150)
plt.show()
六、Git 常用命令
# 初始化
git init # 初始化仓库
git clone <url> # 克隆远程仓库
# 配置
git config --global user.name "你的名字"
git config --global user.email "你的邮箱"
# 日常操作
git status # 查看状态
git add . # 添加所有文件
git add file.txt # 添加指定文件
git commit -m "提交信息" # 提交
git push origin main # 推送到远程
git pull origin main # 拉取更新
# 分支
git branch # 查看分支
git branch feature # 创建分支
git checkout feature # 切换分支
git checkout -b feature # 创建并切换分支
git merge feature # 合并分支
# 查看
git log # 查看提交历史
git diff # 查看差异
git remote -v # 查看远程仓库
小 Demo:完整提交流程
# 1. 初始化仓库
git init
# 2. 添加文件
git add .
# 3. 提交
git commit -m "初始化项目"
# 4. 添加远程仓库
git remote add origin https://github.com/user/repo.git
# 5. 推送
git push -u origin main
七、完整实战 Demo
把所有技能串起来:读取 CSV → 清洗 → 分析 → 存数据库 → 可视化
import pandas as pd
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
# 1. 读取数据
df = pd.read_csv('sales.csv')
# 2. 数据清洗
df = df.dropna() # 删除缺失值
df = df.drop_duplicates() # 删除重复值
df['date'] = pd.to_datetime(df['date']) # 转换日期类型
# 3. 数据分析
df['sales'] = df['quantity'] * df['price']
monthly_sales = df.groupby(df['date'].dt.month)['sales'].sum()
# 4. 存入数据库
engine = create_engine('postgresql://postgres:123456@localhost:5432/mydb')
monthly_sales.to_sql('monthly_sales', engine, if_exists='replace')
# 5. 可视化
plt.figure(figsize=(10, 6))
monthly_sales.plot(kind='bar')
plt.title('月度销售额')
plt.xlabel('月份')
plt.ylabel('销售额')
plt.savefig('monthly_sales.png', dpi=150)
plt.show()
print("数据分析完成!")
八、方法速查表
| 类别 | 常用方法 |
|---|---|
| String | upper(), lower(), split(), replace(), strip(), join(), find() |
| List | append(), insert(), remove(), pop(), sort(), reverse(), extend() |
| Dict | get(), keys(), values(), items(), pop(), update(), setdefault() |
| Pandas | read_csv(), head(), groupby(), merge(), fillna(), to_sql() |
| NumPy | array(), reshape(), sum(), mean(), std(), max(), min(), argmax() |
| SQLAlchemy | create_engine(), query(), add(), commit(), filter_by() |
| Matplotlib | plot(), bar(), scatter(), hist(), pie(), savefig(), subplots() |
| Git | init, add, commit, push, pull, branch, merge, log |
九、学习成果
| 项目 | 完成情况 |
|---|---|
| 学习天数 | 26 天 |
| 练习题数 | 400+ 道 |
| 项目作品 | 1 个(天气数据分析平台) |
| 博客文章 | 8 篇 |
| GitHub | 1 个仓库 |
十、下一步计划
第二阶段学习内容:
| 周次 | 内容 |
|---|---|
| 第1-2周 | Airflow 任务调度 |
| 第3-4周 | Spark 分布式计算 |
| 第5-6周 | dbt 数据建模 |
| 第7-8周 | 综合项目 |
总结:第一阶段打下了 Python 数据处理的基础,第二阶段将学习更专业的数据工程工具。继续加油!💪
更多推荐



所有评论(0)