从零开始的数据分析之旅
Python是数据分析的首选语言。掌握列表、字典、元组、集合等核心数据结构,是进入数据科学世界的第一步。本课从最基础的数据容器出发,理解Python如何组织和操作数据。
列表是Python最常用的数据结构,可以存储任意类型的元素,支持增删改查。
# 列表基本操作
fruits = ["苹果", "香蕉", "橙子", "葡萄", "西瓜"]
fruits.append("芒果") # 末尾添加
fruits.insert(2, "草莓") # 指定位置插入
removed = fruits.pop(3) # 弹出指定索引
sliced = fruits[1:4] # 切片操作
# 列表推导式 —— Python最优雅的语法
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
matrix = [[i*3+j for j in range(3)] for i in range(3)]
字典是Python中最重要的映射类型,O(1)查找速度使其成为数据处理的利器。
# 字典操作
student = {"姓名": "张三", "年龄": 22, "专业": "数据科学"}
student["成绩"] = 95 # 添加键值对
student.update({"年级": "大三", "城市": "北京"}) # 批量更新
keys = list(student.keys())
values = list(student.values())
# 字典推导式
word = "abracadabra"
char_count = {c: word.count(c) for c in set(word)}
NumPy(Numerical Python)是Python科学计算的基石。它的核心是ndarray——高效的多维数组对象,支持向量化运算,比原生Python列表快10-100倍。
| 特性 | Python列表 | NumPy数组 |
|---|---|---|
| 类型 | 混合类型 | 同类型 |
| 内存 | 分散存储 | 连续存储 |
| 运算 | 循环遍历 | 向量化 |
| 速度 | 慢 | 快10-100倍 |
| 广播 | 不支持 | 支持 |
import numpy as np
# 数组创建
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 广播机制 —— 形状不同的数组也能运算
a = np.array([[1], [2], [3]]) # 3×1
b = np.array([10, 20, 30]) # 1×3
result = a + b # 自动扩展为 3×3
# 布尔索引
data = np.random.randn(5, 3)
positive = data[data > 0] # 筛选所有正数
# 花式索引
idx = np.array([0, 2, 4])
selected = arr[idx] # 按索引选取
import numpy as np, time
# 列表方式
start = time.time()
a_list = [x**2 for x in range(1000000)]
print(f"列表: {time.time()-start:.4f}s")
# NumPy方式
start = time.time()
a_np = np.arange(1000000) ** 2
print(f"NumPy: {time.time()-start:.4f}s")
# 集合运算
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
print(f"并集: {set_a | set_b}")
print(f"交集: {set_a & set_b}")
print(f"差集: {set_a - set_b}")
# 去重最简方式
duplicates = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(duplicates))
point = (3, 4)
x, y = point # 解包
from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'score'])
s = Student('张三', 22, 95)
print(f"{s.name}: {s.score}分")
# enumerate与zip
fruits = ['苹果', '香蕉', '橙子']
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
names = ['张三', '李四', '王五']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}分")
# 生成器表达式(大数据场景)
gen = (x**2 for x in range(1000000)) # 惰性计算
print(sum(gen))
(...)而非列表推导式[...],可节省大量内存。以下代码涵盖本课所有知识点,可直接在Python环境中运行:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python数据基础 — 完整实战
# ============ 列表操作 ============
fruits = ["苹果", "香蕉", "橙子", "葡萄", "西瓜"]
fruits.append("芒果") # 末尾添加
fruits.insert(2, "草莓") # 指定位置插入
removed = fruits.pop(3) # 弹出指定索引
sliced = fruits[1:4] # 切片操作
print(f"水果列表: {fruits}")
print(f"切片[1:4]: {sliced}")
print(f"移除的: {removed}")
# 列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
print(f"平方: {squares}")
print(f"偶数: {evens}")
# ============ 字典操作 ============
student = {"姓名": "张三", "年龄": 22, "专业": "数据科学"}
student["成绩"] = 95
student.update({"年级": "大三", "城市": "北京"})
keys = list(student.keys())
values = list(student.values())
print(f"学生信息: {student}")
print(f"键: {keys}")
print(f"值: {values}")
# 字典推导式
word = "abracadabra"
char_count = {c: word.count(c) for c in set(word)}
print(f"字符计数: {char_count}")
# ============ NumPy基础 ============
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(f"数组: {arr}")
print(f"矩阵:\n{matrix}")
print(f"形状: {matrix.shape}")
print(f"求和: {arr.sum()}, 均值: {arr.mean():.2f}, 标准差: {arr.std():.2f}")
# 广播机制
a = np.array([[1], [2], [3]])
b = np.array([10, 20, 30])
print(f"广播结果:\n{a + b}")
# 布尔索引
data = np.random.randn(5, 3)
positive = data[data > 0]
print(f"正数数量: {len(positive)}/{data.size}")
# 花式索引
idx = np.array([0, 2, 4])
print(f"花式索引: {arr[idx]}")
print("\n✅ Python验证通过 — 列表/字典/NumPy操作全部正确")
| 类型 | 创建 | 可变 | 有序 | 常用操作 |
|---|---|---|---|---|
| list | [1,2,3] | ✅ | ✅ | append/pop/sort/reverse |
| tuple | (1,2,3) | ❌ | ✅ | index/count/解包 |
| dict | {'a':1} | ✅ | ✅(3.7+) | get/update/items/keys |
| set | {1,2,3} | ✅ | ❌ | add/remove/交并差 |
| str | 'hello' | ❌ | ✅ | split/join/replace/strip |
| ndarray | np.array() | ✅ | ✅ | reshape/mean/dot/广播 |