库名称 | 核心功能 | 使用场景 | 优势 |
---|---|---|---|
NumPy | 多维数组 | 科学计算 | 速度快 |
Pandas | DataFrame | 数据分析 | 接口友好 |
Matplotlib | 图表绘制 | 数据可视化 | 功能全面 |
Requests | HTTP请求 | 网络爬虫 | 简单易用 |
Flask | Web框架 | 网站开发 | 轻量灵活 |
pip install numpy pandas matplotlib requests flask
import numpy as np
# 创建数组
arr = np.array([[1, 2], [3, 4]])
print("原数组:\n", arr)
# 矩阵乘法
result = arr @ arr.T # 矩阵转置后相乘
print("矩阵乘积:\n", result)
import pandas as pd
# 读取CSV数据
df = pd.read_csv("sales.csv")
print("前5行数据:\n", df.head())
# 计算统计指标
print("月销售额统计:")
print(df.groupby('month')['amount'].sum())
import matplotlib.pyplot as plt
# 准备数据
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
# 绘制折线图
plt.plot(x, y, marker='o')
plt.title("销售趋势")
plt.xlabel("季度")
plt.ylabel("销售额(万)")
plt.savefig("sales_trend.png")
import requests
# 获取天气数据
url = "http://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=YOUR_KEY"
response = requests.get(url)
data = response.json()
print("北京当前温度:", data["main"]["temp"] - 273.15, "℃")
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "欢迎来到我的第一个网站!
"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
# 案例1输出:
矩阵乘积:
[[ 5 11]
[11 25]]
# 案例4输出:
北京当前温度: 22.35 ℃
# 案例5访问:
浏览器访问 http://localhost:5000 显示欢迎页面
操作 | 纯Python | NumPy | 加速比 |
---|---|---|---|
数组求和 | 0.015 | 0.0001 | 150x |
矩阵乘法 | 12.3 | 0.02 | 615x |
标准差计算 | 0.25 | 0.001 | 250x |
优先使用向量化操作
# 正确:使用NumPy向量化计算
arr = np.array([1,2,3])
result = arr * 2
# 错误:使用Python循环
result = [x*2 for x in arr]
批量数据读取
# 分块读取大文件
chunk_iter = pd.read_csv("big_data.csv", chunksize=10000)
for chunk in chunk_iter:
process(chunk)
图表样式优化
plt.style.use('seaborn') # 使用更美观的样式
请求重试机制
from requests.adapters import HTTPAdapter
session = requests.Session()
session.mount('http://', HTTPAdapter(max_retries=3))
Flask路由参数化
@app.route('/user/' )
def show_user(username):
return f"用户:{username}"
忘记导入库
arr = np.array([1,2,3]) # 报错:未导入numpy
混合数据类型
df['price'] = '100元' # 导致无法数值计算
阻塞主线程
# Flask中执行耗时操作
@app.route('/slow')
def slow_page():
time.sleep(10) # 导致服务阻塞
return "Done"
未关闭文件
f = open('data.txt')
content = f.read() # 正确应使用with语句
API密钥硬编码
# 直接将密钥写在代码中
api_key = "123456"
打印数据结构
print(df.info()) # 查看DataFrame结构
可视化调试
plt.plot(arr) # 绘制数组图形辅助分析
plt.show()
使用Jupyter Notebook
# 交互式逐步执行代码块
学习建议:从实际项目入手,先完成再完善,逐步掌握各库的核心API。