Python数据分析黄金三角:Numpy、Pandas、Matplotlib实战教程

发布时间:2026/7/14 4:00:32
Python数据分析黄金三角:Numpy、Pandas、Matplotlib实战教程 如果你正在学习Python数据分析或者工作中需要处理数据那么numpy、pandas和matplotlib这三个库你一定绕不开。但很多初学者会遇到这样的困惑为什么需要三个不同的库它们各自解决什么问题学完之后能做什么实际上这三个库构成了Python数据分析的黄金三角numpy负责底层数值计算pandas处理表格数据matplotlib进行数据可视化。掌握了它们你就能完成从数据清洗、分析到可视化的完整流程。本文将通过一个完整的实战案例带你零基础学会这三个核心库的使用。不同于其他教程只讲基础语法我会重点展示如何将它们结合起来解决实际问题并分享实际项目中容易踩的坑。1. 环境准备与工具安装在开始之前我们需要确保环境配置正确。推荐使用Anaconda它已经包含了我们需要的所有库。1.1 安装Python环境如果你还没有安装Python建议直接安装Anaconda# 下载Anaconda选择Python 3.8版本 # 官网https://www.anaconda.com/products/individual # 验证安装 conda --version python --version1.2 安装必要的库如果使用纯净的Python环境需要单独安装这三个库pip install numpy pandas matplotlib1.3 验证安装创建一个Python文件验证安装是否成功# test_installation.py import numpy as np import pandas as pd import matplotlib.pyplot as plt print(numpy版本:, np.__version__) print(pandas版本:, pd.__version__) print(matplotlib版本:, plt.__version__) # 如果都能正常输出版本号说明安装成功2. Numpy科学计算的基础2.1 为什么需要Numpy在数据分析中我们经常要处理大量的数值计算。Python原生的列表在处理大量数据时效率很低而Numpy的ndarrayN维数组在底层用C语言实现计算速度能快上百倍。2.2 核心概念Numpy数组import numpy as np # 创建Python列表 python_list [1, 2, 3, 4, 5] # 转换为Numpy数组 numpy_array np.array(python_list) print(Numpy数组:, numpy_array) print(数组形状:, numpy_array.shape) print(数组数据类型:, numpy_array.dtype)2.3 实战案例农产品产量预测假设我们要根据气候数据预测苹果产量这是一个典型的数据分析场景。# 定义气候数据温度、降雨量、湿度 kanto [73, 67, 43] # 关东地区 johto [91, 88, 64] # 城都地区 hoenn [87, 134, 58] # 丰缘地区 # 定义影响因子权重通过历史数据得出 weights [0.3, 0.2, 0.5] # 温度、降雨量、湿度的权重 # 传统Python方法计算点积 def python_dot_product(region, weights): result 0 for x, w in zip(region, weights): result x * w return result print(关东地区产量(Python):, python_dot_product(kanto, weights)) # Numpy方法 kanto_np np.array(kanto) weights_np np.array(weights) # 方法1使用dot函数 print(关东地区产量(Numpy dot):, np.dot(kanto_np, weights_np)) # 方法2使用元素乘法和sum print(关东地区产量(Numpy sum):, (kanto_np * weights_np).sum())2.4 性能对比Numpy的优势import time # 创建大规模数据 size 1000000 arr1 list(range(size)) arr2 list(range(size, size*2)) arr1_np np.array(arr1) arr2_np np.array(arr2) # Python循环方式 start_time time.time() result_python 0 for i in range(size): result_python arr1[i] * arr2[i] python_time time.time() - start_time # Numpy方式 start_time time.time() result_numpy np.dot(arr1_np, arr2_np) numpy_time time.time() - start_time print(fPython循环耗时: {python_time:.4f}秒) print(fNumpy点积耗时: {numpy_time:.4f}秒) print(f性能提升: {python_time/numpy_time:.1f}倍)2.5 多维数组操作# 创建二维数组矩阵 climate_data np.array([ [73, 67, 43], # 关东 [91, 88, 64], # 城都 [87, 134, 58], # 丰缘 [102, 43, 37], # 神奥 [69, 96, 70] # 合众 ]) print(气候数据形状:, climate_data.shape) print(气候数据:\n, climate_data) # 矩阵乘法计算所有地区产量 yields climate_data weights_np # 运算符表示矩阵乘法 print(所有地区产量:, yields)3. Pandas表格数据处理利器3.1 从Numpy到Pandas虽然Numpy适合数值计算但在处理真实的表格数据时如CSV、ExcelPandas提供了更强大的功能。import pandas as pd # 创建DataFrame data { 地区: [关东, 城都, 丰缘, 神奥, 合众], 温度: [73, 91, 87, 102, 69], 降雨量: [67, 88, 134, 43, 96], 湿度: [43, 64, 58, 37, 70] } df pd.DataFrame(data) print(原始数据:) print(df)3.2 数据清洗与预处理真实数据往往存在缺失值、异常值等问题Pandas提供了完善的处理工具。# 添加产量计算 df[产量] df[温度] * 0.3 df[降雨量] * 0.2 df[湿度] * 0.5 print(添加产量后的数据:) print(df) # 处理缺失值模拟有缺失数据的情况 df_missing df.copy() df_missing.loc[2, 降雨量] None # 设置一个缺失值 print(有缺失值的数据:) print(df_missing) # 填充缺失值 df_filled df_missing.fillna({降雨量: df_missing[降雨量].mean()}) print(填充缺失值后:) print(df_filled)3.3 数据筛选与排序# 筛选高产量地区 high_yield df[df[产量] 70] print(高产地区:) print(high_yield) # 按产量排序 sorted_df df.sort_values(产量, ascendingFalse) print(按产量排序:) print(sorted_df) # 多条件筛选 complex_filter df[(df[温度] 80) (df[湿度] 60)] print(温度80且湿度60的地区:) print(complex_filter)3.4 实战案例COVID-19数据分析让我们用一个真实的数据集来练习Pandas的强大功能。# 创建模拟的疫情数据 dates pd.date_range(2020-01-01, periods100, freqD) covid_data { date: dates, new_cases: np.random.randint(100, 5000, 100), new_deaths: np.random.randint(1, 100, 100), new_tests: np.random.randint(1000, 20000, 100) } covid_df pd.DataFrame(covid_data) print(疫情数据前5行:) print(covid_df.head()) print(\n数据基本信息:) print(covid_df.info()) print(\n数值列统计信息:) print(covid_df.describe())3.5 高级数据处理技巧# 添加时间维度分析 covid_df[month] covid_df[date].dt.month covid_df[day_of_week] covid_df[date].dt.day_name() # 按月分组统计 monthly_stats covid_df.groupby(month).agg({ new_cases: sum, new_deaths: sum, new_tests: sum }) print(月度统计:) print(monthly_stats) # 计算阳性率 covid_df[positive_rate] covid_df[new_cases] / covid_df[new_tests] # 添加移动平均消除日波动 covid_df[cases_ma] covid_df[new_cases].rolling(window7).mean() print(添加移动平均后的数据:) print(covid_df[[date, new_cases, cases_ma]].head(10))4. Matplotlib数据可视化4.1 基础绘图入门import matplotlib.pyplot as plt # 设置中文字体解决中文显示问题 plt.rcParams[font.sans-serif] [SimHei] # 用来正常显示中文标签 plt.rcParams[axes.unicode_minus] False # 用来正常显示负号 # 基础折线图 plt.figure(figsize(10, 6)) plt.plot(covid_df[date], covid_df[new_cases]) plt.title(每日新增病例趋势) plt.xlabel(日期) plt.ylabel(新增病例数) plt.grid(True) plt.show()4.2 多子图与样式美化# 创建多个子图 fig, axes plt.subplots(2, 2, figsize(15, 10)) # 子图1新增病例趋势 axes[0, 0].plot(covid_df[date], covid_df[new_cases], b-, label每日新增) axes[0, 0].plot(covid_df[date], covid_df[cases_ma], r-, label7日移动平均) axes[0, 0].set_title(新增病例趋势) axes[0, 0].legend() axes[0, 0].grid(True) # 子图2阳性率趋势 axes[0, 1].plot(covid_df[date], covid_df[positive_rate] * 100, g-) axes[0, 1].set_title(检测阳性率(%)) axes[0, 1].grid(True) # 子图3月度汇总柱状图 monthly_cases covid_df.groupby(month)[new_cases].sum() axes[1, 0].bar(monthly_cases.index, monthly_cases.values, colororange) axes[1, 0].set_title(月度病例汇总) axes[1, 0].set_xlabel(月份) # 子图4散点图病例vs检测 axes[1, 1].scatter(covid_df[new_tests], covid_df[new_cases], alpha0.5) axes[1, 1].set_xlabel(检测数量) axes[1, 1].set_ylabel(病例数量) axes[1, 1].set_title(检测数量vs病例数量) plt.tight_layout() plt.show()4.3 高级可视化技巧# 使用Seaborn样式美化 plt.style.use(seaborn-v0_8) # 创建更专业的图表 fig, (ax1, ax2) plt.subplots(1, 2, figsize(15, 5)) # 箱线图显示分布 covid_df[month] covid_df[date].dt.month monthly_data [covid_df[covid_df[month] month][new_cases] for month in range(1, 13)] ax1.boxplot(monthly_data) ax1.set_title(各月新增病例分布) ax1.set_xlabel(月份) ax1.set_ylabel(新增病例数) # 热力图需要pivot数据 heatmap_data covid_df.pivot_table(valuesnew_cases, indexcovid_df[date].dt.dayofweek, columnscovid_df[date].dt.month, aggfuncmean) im ax2.imshow(heatmap_data, cmapYlOrRd) ax2.set_title(每日病例热力图周vs月) ax2.set_xlabel(月份) ax2.set_ylabel(星期几) plt.colorbar(im, axax2) plt.tight_layout() plt.show()5. 完整实战案例气候数据分析现在让我们把三个库结合起来完成一个完整的数据分析项目。5.1 数据准备与清洗# 模拟气候数据 np.random.seed(42) # 确保结果可重现 years range(2000, 2021) regions [北京, 上海, 广州, 成都, 武汉] # 生成模拟数据 data [] for year in years: for region in regions: temp np.random.normal(15, 5) # 温度 rainfall np.random.gamma(2, 50) # 降雨量 humidity np.random.normal(60, 10) # 湿度 data.append({ year: year, region: region, temperature: max(0, temp), # 温度不能为负 rainfall: max(0, rainfall), # 降雨量不能为负 humidity: max(0, min(100, humidity)) # 湿度在0-100之间 }) climate_df pd.DataFrame(data) print(气候数据概览:) print(climate_df.head())5.2 数据分析与计算# 使用Numpy进行数值计算 # 计算每个地区的年平均气候指标 regional_stats climate_df.groupby(region).agg({ temperature: [mean, std], rainfall: [mean, std], humidity: [mean, std] }) print(地区气候统计:) print(regional_stats) # 使用Pandas进行时间序列分析 climate_pivot climate_df.pivot_table( values[temperature, rainfall, humidity], indexyear, columnsregion, aggfuncmean ) print(年度气候数据透视表:) print(climate_pivot.head())5.3 数据可视化展示# 创建综合可视化仪表板 fig plt.figure(figsize(18, 12)) # 1. 温度趋势图 ax1 plt.subplot(2, 2, 1) for region in regions: region_data climate_df[climate_df[region] region] yearly_temp region_data.groupby(year)[temperature].mean() ax1.plot(yearly_temp.index, yearly_temp.values, labelregion, markero) ax1.set_title(各地区年平均温度趋势) ax1.set_xlabel(年份) ax1.set_ylabel(温度(°C)) ax1.legend() ax1.grid(True) # 2. 降雨量分布箱线图 ax2 plt.subplot(2, 2, 2) rainfall_data [climate_df[climate_df[region] region][rainfall] for region in regions] ax2.boxplot(rainfall_data, labelsregions) ax2.set_title(各地区降雨量分布) ax2.set_ylabel(降雨量(mm)) # 3. 湿度热力图 ax3 plt.subplot(2, 2, 3) heatmap_data climate_df.pivot_table(valueshumidity, indexyear, columnsregion, aggfuncmean) im ax3.imshow(heatmap_data, cmapBlues, aspectauto) ax3.set_title(各地区湿度热力图) ax3.set_xlabel(地区) ax3.set_ylabel(年份) ax3.set_xticks(range(len(regions))) ax3.set_xticklabels(regions) plt.colorbar(im, axax3) # 4. 气候指标相关性散点图 ax4 plt.subplot(2, 2, 4) scatter ax4.scatter(climate_df[temperature], climate_df[rainfall], cclimate_df[humidity], cmapviridis, alpha0.6) ax4.set_xlabel(温度(°C)) ax4.set_ylabel(降雨量(mm)) ax4.set_title(温度-降雨量关系颜色表示湿度) plt.colorbar(scatter, axax4, label湿度(%)) plt.tight_layout() plt.show()5.4 高级分析与洞察# 使用Numpy进行高级统计分析 # 计算气候变化的斜率趋势分析 def calculate_trend(years, values): 计算时间序列的趋势斜率 x np.array(years) y np.array(values) # 线性回归 slope np.polyfit(x, y, 1)[0] return slope # 分析每个地区的气候变化趋势 trend_results [] for region in regions: region_data climate_df[climate_df[region] region] yearly_avg region_data.groupby(year).mean() temp_trend calculate_trend(yearly_avg.index, yearly_avg[temperature]) rain_trend calculate_trend(yearly_avg.index, yearly_avg[rainfall]) trend_results.append({ region: region, temperature_trend: temp_trend, rainfall_trend: rain_trend, warming : temp_trend 0 # 是否变暖 }) trend_df pd.DataFrame(trend_results) print(气候变化趋势分析:) print(trend_df)6. 常见问题与解决方案6.1 安装与导入问题问题1导入时报错No module named numpy# 解决方案重新安装 pip uninstall numpy pandas matplotlib pip install numpy pandas matplotlib问题2中文显示乱码# 在代码开头添加 import matplotlib.pyplot as plt plt.rcParams[font.sans-serif] [SimHei, DejaVu Sans] plt.rcParams[axes.unicode_minus] False6.2 数据处理常见错误问题3SettingWithCopyWarning警告# 错误方式 df_subset df[df[value] 100] df_subset[new_col] 1 # 可能产生警告 # 正确方式 df_subset df[df[value] 100].copy() df_subset[new_col] 1问题4内存不足处理大数据# 使用分块读取大文件 chunk_size 10000 chunks pd.read_csv(large_file.csv, chunksizechunk_size) for chunk in chunks: # 处理每个数据块 process_chunk(chunk)6.3 可视化优化技巧问题5图形显示不清晰# 提高图形质量 plt.figure(figsize(12, 8), dpi300) # 增加尺寸和分辨率 plt.rcParams[figure.dpi] 150 # 全局设置分辨率 plt.rcParams[savefig.dpi] 300 # 保存图片的分辨率7. 最佳实践与性能优化7.1 代码组织最佳实践# 良好的代码结构示例 def prepare_climate_data(file_path): 准备气候数据 df pd.read_csv(file_path) # 数据清洗 df df.dropna() # 删除缺失值 df df[df[temperature] -50] # 过滤异常值 return df def analyze_trends(df): 分析趋势 # 分组计算 trends df.groupby(region).apply( lambda x: np.polyfit(x[year], x[temperature], 1)[0] ) return trends def create_visualization(df, output_path): 创建可视化 plt.figure(figsize(10, 6)) # ... 绘图代码 plt.savefig(output_path, bbox_inchestight) plt.close() # 主程序 def main(): data prepare_climate_data(climate_data.csv) trends analyze_trends(data) create_visualization(data, climate_trends.png)7.2 性能优化技巧# 1. 使用向量化操作代替循环 # 慢循环方式 result [] for i in range(len(df)): result.append(df[a][i] df[b][i]) # 快向量化方式 result df[a] df[b] # 2. 使用合适的数据类型 df[column] df[column].astype(category) # 分类数据 df[column] df[column].astype(float32) # 节省内存 # 3. 使用query方法进行筛选 # 更高效的内存使用 result df.query(temperature 20 and rainfall 100)通过这个完整的教程你应该已经掌握了numpy、pandas和matplotlib的核心用法。记住数据分析的关键在于实践尝试用这些工具解决你遇到的实际问题才能真正掌握它们。