7 minutes
Python 基础速览
Python 是数据分析领域最流行的编程语言。它的语法简洁清晰,学习曲线平缓,配合丰富的第三方库,可以高效地完成从数据采集到可视化呈现的全流程工作。
这篇文章不是 Python 的完整教程,而是针对数据分析场景的速览。如果你完全没有编程经验,建议结合官方教程或在线课程一起学习。
基本数据类型
Python 有几种基本数据类型,你在数据分析中会频繁用到:
# 整数 (int)
age = 25
count = -100
large_number = 1_000_000 # Python 3.6+ 支持下划线分隔符
# 浮点数 (float)
price = 29.99
pi = 3.14159
scientific = 1.5e-4 # 科学计数法,等于 0.00015
# 字符串 (str)
name = "数据分析"
description = 'Python 入门'
multiline = """这是多行字符串
可以跨越多行
非常方便"""
# 布尔值 (bool)
is_active = True
is_finished = False
# None 类型
result = None # 表示"没有值",类似于其他语言的 null
类型转换
# 字符串转整数
int("123") # 123
# 整数转字符串
str(456) # "456"
# 字符串转浮点数
float("3.14") # 3.14
# 检查类型
type(42) # <class 'int'>
isinstance(3.14, float) # True
数据结构
Python 内置了四种主要的数据结构,它们是数据处理的基础。
列表 (List)
列表是有序、可变的序列,用方括号 [] 表示:
# 创建列表
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]] # 嵌套列表
# 索引(从 0 开始)
numbers[0] # 1
numbers[-1] # 5(最后一个元素)
numbers[-2] # 4(倒数第二个元素)
# 切片 [start:stop:step]
numbers[1:3] # [2, 3](不包含 end 索引)
numbers[:3] # [1, 2, 3](从头到索引 3)
numbers[::2] # [1, 3, 5](步长为 2)
numbers[::-1] # [5, 4, 3, 2, 1](反转)
# 常用方法
numbers.append(6) # 追加:[1, 2, 3, 4, 5, 6]
numbers.insert(0, 0) # 插入:[0, 1, 2, 3, 4, 5, 6]
numbers.remove(3) # 删除第一个 3
popped = numbers.pop() # 弹出并返回最后一个元素
numbers.sort() # 排序(原地修改)
sorted(numbers) # 返回排序后的新列表
# 列表推导式(非常 Pythonic)
squares = [x ** 2 for x in range(10)] # [0, 1, 4, 9, ..., 81]
evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, ..., 18]
元组 (Tuple)
元组是不可变的序列,用圆括号 () 表示:
# 创建元组
point = (3, 5)
rgb = (255, 128, 0)
single = (1,) # 单个元素需要加逗号
empty = () # 空元组
# 解包(unpacking)
x, y = point # x=3, y=5
a, b, c = rgb
# 元组不可变,不能修改元素
# point[0] = 10 # 这行会报错
# 用元组作为字典键(列表不行)
location = {(40.7128, -74.0060): "纽约"}
字典 (Dict)
字典是键值对的集合,用花括号 {} 表示:
# 创建字典
student = {
"name": "张三",
"age": 20,
"scores": [85, 92, 78]
}
# 访问和修改
student["name"] # "张三"
student.get("grade", "N/A") # 安全访问,不存在时返回默认值
student["age"] = 21 # 修改值
student["gender"] = "男" # 添加新键值对
# 删除
del student["gender"] # 删除键值对
popped = student.pop("age") # 弹出并返回值
# 遍历
for key, value in student.items():
print(f"{key}: {value}")
for key in student.keys(): # 仅遍历键
for value in student.values(): # 仅遍历值
# 字典推导式
squares_dict = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
集合 (Set)
集合是无序、不重复的元素集合:
# 创建集合
unique_numbers = {1, 2, 3, 3, 2, 1} # {1, 2, 3}
empty_set = set() # 空集合(不能用 {},那是空字典)
set_from_list = set([1, 2, 2, 3]) # {1, 2, 3}
# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a & b # 交集: {3, 4}
a | b # 并集: {1, 2, 3, 4, 5, 6}
a - b # 差集: {1, 2}
a ^ b # 对称差: {1, 2, 5, 6}
# 常见用途:去重
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers)) # [1, 2, 3, 4]
控制流
条件判断
score = 85
if score >= 90:
grade = "优秀"
elif score >= 80:
grade = "良好"
elif score >= 70:
grade = "中等"
elif score >= 60:
grade = "及格"
else:
grade = "不及格"
# 三元表达式
status = "成年" if age >= 18 else "未成年"
# 逻辑运算符
if 0 < score < 100: # Python 支持链式比较
print("有效分数")
if score >= 60 and score < 90:
print("不是优秀但及格了")
if score < 60 or score > 100:
print("异常分数")
循环
# for 循环
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(fruit)
# 带索引的遍历
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# 遍历字典
scores = {"语文": 85, "数学": 92, "英语": 78}
for subject, score in scores.items():
print(f"{subject}: {score}")
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# break 和 continue
for i in range(10):
if i == 3:
continue # 跳过当前迭代
if i == 7:
break # 完全退出循环
print(i)
函数
函数是组织代码、避免重复的基本方式。
# 基本函数定义
def calculate_bmi(weight, height):
"""计算 BMI 指数(函数文档字符串)"""
bmi = weight / (height ** 2)
return bmi
result = calculate_bmi(70, 1.75) # 22.86
# 默认参数
def greet(name, greeting="你好"):
return f"{greeting},{name}"
greet("张三") # "你好,张三"
greet("李四", "早上好") # "早上好,李四"
# 可变参数 (*args 和 **kwargs)
def summarize(*args, **kwargs):
"""args 接收任意数量的位置参数,kwargs 接收关键字参数"""
print(f"位置参数: {args}")
print(f"关键字参数: {kwargs}")
summarize(1, 2, 3, name="Python", version=3.11)
# 位置参数: (1, 2, 3)
# 关键字参数: {'name': 'Python', 'version': 3.11}
# 返回值
def stats(numbers):
"""返回多个值(实际是元组)"""
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = stats([1, 2, 3, 4, 5])
Lambda 函数
Lambda 是小型匿名函数,在数据分析中非常有用(特别是与 Pandas 配合时):
# 基本 lambda
square = lambda x: x ** 2
square(5) # 25
# 多参数 lambda
add = lambda a, b: a + b
add(3, 4) # 7
# 配合 sorted 使用
students = [("张三", 85), ("李四", 92), ("王五", 78)]
sorted(students, key=lambda student: student[1]) # 按分数排序
列表推导式 (List Comprehensions)
列表推导式是 Python 最优雅的特性之一,在数据处理中经常用到:
# 基本形式:[expression for item in iterable]
squares = [x ** 2 for x in range(10)]
# 带条件筛选
evens = [x for x in range(20) if x % 2 == 0]
# 双重循环
pairs = [(x, y) for x in [1, 2, 3] for y in [4, 5, 6]]
# 字典推导式
word_length = {word: len(word) for word in ["Python", "数据分析", "AI"]}
# 集合推导式
unique_lengths = {len(word) for word in ["hello", "world", "hi"]}
# 生成器表达式(节省内存)
large_sum = sum(x ** 2 for x in range(1000000)) # 没有方括号,是生成器
错误处理
数据分析中经常会遇到数据质量问题,合理的错误处理能让你的代码更健壮:
# try/except 基本用法
try:
value = int(input("请输入数字:"))
result = 100 / value
print(f"结果是: {result}")
except ValueError:
print("输入的不是有效数字")
except ZeroDivisionError:
print("不能除以零")
except Exception as e:
print(f"发生了未知错误: {e}")
finally:
print("无论如何都会执行这段代码")
# 实战:安全地转换数据类型
def safe_convert_to_float(value):
"""安全地将值转换为浮点数"""
try:
return float(value)
except (ValueError, TypeError):
return float("nan") # 返回缺失值标记
# 实战:安全读取文件
def safe_read_file(filename):
try:
with open(filename, "r", encoding="utf-8") as f:
return f.read()
except FileNotFoundError:
print(f"文件 {filename} 不存在")
return ""
except IOError:
print(f"读取文件 {filename} 时出错")
return ""
文件读写
数据分析的起点通常是读取数据文件:
# 读取文本文件
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部内容
# content = f.readline() # 读取一行
# content = f.readlines() # 读取所有行到列表
# 写入文本文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("第一行\n")
f.write("第二行\n")
# 追加到文件
with open("output.txt", "a", encoding="utf-8") as f:
f.write("追加的行\n")
# 读取 CSV 文件(不依赖 Pandas)
def read_csv_simple(filename):
"""简单手动读取 CSV 文件"""
with open(filename, "r", encoding="utf-8") as f:
lines = f.readlines()
header = lines[0].strip().split(",")
data = []
for line in lines[1:]:
values = line.strip().split(",")
row = dict(zip(header, values))
data.append(row)
return data
模块和包
良好的代码组织能让项目更易维护:
# 导入整个模块
import math
print(math.pi)
print(math.sqrt(16))
# 导入特定函数/变量
from math import pi, sqrt
print(sqrt(25))
# 起别名
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 从模块导入所有内容(谨慎使用)
from math import *
# 自定义模块
# 创建文件 my_analysis.py,内容为:
# def clean_data(df):
# return df.dropna()
#
# 然后在其他文件中:
# from my_analysis import clean_data
常用内置模块
import os # 操作系统接口
import sys # Python 解释器信息
import json # JSON 数据处理
import csv # CSV 文件处理
import re # 正则表达式
import datetime # 日期和时间
import random # 随机数生成
import math # 数学函数
import collections # 高级容器类型
实践练习
把上面的知识点组合起来,做一个简单的数据分析小程序:
import csv
import random
from statistics import mean, median, stdev
# 生成示例销售数据
def generate_sales_data(days=30):
"""生成指定天数的模拟销售数据"""
products = ["笔记本电脑", "手机", "耳机", "键盘", "鼠标"]
data = []
for day in range(1, days + 1):
for product in products:
sales = random.randint(1, 50)
price = random.choice([2999, 4999, 199, 299, 99])
data.append({
"day": day,
"product": product,
"sales": sales,
"price": price,
"revenue": sales * price
})
return data
# 分析数据
def analyze_sales(data):
"""分析销售数据"""
# 计算总收入
total_revenue = sum(row["revenue"] for row in data)
print(f"总收入: {total_revenue:,} 元")
# 按产品分组统计
product_stats = {}
for row in data:
product = row["product"]
if product not in product_stats:
product_stats[product] = {"total": 0, "count": 0}
product_stats[product]["total"] += row["revenue"]
product_stats[product]["count"] += row["sales"]
print("\n产品销售统计:")
for product, stats in sorted(product_stats.items()):
avg_price = stats["total"] / stats["count"] if stats["count"] > 0 else 0
print(f"{product}: 总收入 {stats['total']:>8,} 元, "
f"售出 {stats['count']:>3} 件, "
f"均价 {avg_price:>7.2f} 元")
# 执行分析
sales_data = generate_sales_data(30)
analyze_sales(sales_data)
下一步
掌握了 Python 基础后,我们就可以开始学习数据分析的核心库了。下一篇将介绍 NumPy,它是 Python 科学计算的基石,为高性能数组运算提供了强大的支持。