Python数据分析实战:Numpy、Pandas、Matplotlib从入门到精通
这次我们来看一个完整的Python数据分析教程从零基础到掌握numpy、pandas和matplotlib三大核心库。如果你正在学习数据分析或者想快速上手数据处理和可视化这篇文章可以直接收藏。数据分析不是高深的理论而是解决实际问题的工具。比如通过气象数据预测苹果产量、分析疫情数据趋势、或者可视化销售数据。Python的numpy负责数值计算pandas处理表格数据matplotlib进行可视化三者结合能解决90%的数据分析需求。本文会带你完成环境搭建、库安装、基础操作到实际案例的全流程。重点不是概念讲解而是可运行的代码和可视化效果验证。无论你是学生、转行者还是业务人员都能跟着步骤跑通。1. 核心能力速览能力项说明技术栈Python Numpy Pandas Matplotlib学习门槛零基础可学需基本Python语法硬件要求普通电脑即可无需GPU主要功能数值计算、表格处理、数据可视化适合场景数据分析、科研计算、商业报表、机器学习预处理数据格式支持CSV、Excel、JSON、数据库等可视化类型折线图、散点图、直方图、条形图、热力图等2. 环境准备与安装2.1 Python环境检查首先确认你已安装Python3.6以上版本。打开命令行输入python --version # 或 python3 --version如果显示版本号说明Python已安装。如果没有去Python官网下载安装包安装时记得勾选Add Python to PATH。2.2 库安装命令一次性安装所有需要的库pip install numpy pandas matplotlib seaborn jupyter如果下载慢可以使用国内镜像pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy pandas matplotlib seaborn jupyter2.3 验证安装打开Python交互环境测试import numpy as np import pandas as pd import matplotlib.pyplot as plt print(所有库导入成功)如果没有报错说明环境准备完成。3. Numpy数值计算实战3.1 从Python列表到Numpy数组传统Python列表计算效率低Numpy数组专门为数值计算优化。# 传统Python列表计算 kanto [73, 67, 43] # 温度、降雨量、湿度 weights [0.3, 0.2, 0.5] def crop_yield(region, weights): result 0 for x, w in zip(region, weights): result x * w return result print(fPython列表计算产量: {crop_yield(kanto, weights)}) # Numpy数组计算 import numpy as np kanto_np np.array([73, 67, 43]) weights_np np.array([0.3, 0.2, 0.5]) # 三种计算方式结果相同 result1 np.dot(kanto_np, weights_np) result2 (kanto_np * weights_np).sum() result3 kanto_np weights_np # 矩阵乘法运算符 print(fNumpy点积: {result1}) print(f元素相乘求和: {result2}) print(f矩阵乘法: {result3})3.2 性能对比Numpy快100倍处理大数据时Numpy的优势更加明显import time # 创建100万元素的大数组 arr1 list(range(1000000)) arr2 list(range(1000000, 2000000)) arr1_np np.array(arr1) arr2_np np.array(arr2) # Python循环计算慢 start_time time.time() result_py 0 for x1, x2 in zip(arr1, arr2): result_py x1 * x2 py_time time.time() - start_time # Numpy计算快 start_time time.time() result_np np.dot(arr1_np, arr2_np) np_time time.time() - start_time print(fPython循环耗时: {py_time:.4f}秒) print(fNumpy计算耗时: {np_time:.4f}秒) print(f加速比: {py_time/np_time:.1f}倍)3.3 多维数组和矩阵运算现实数据往往是多维的Numpy完美支持# 创建5个地区的气候数据矩阵5行3列 climate_data np.array([[73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70]]) print(数据形状:, climate_data.shape) # (5, 3) print(数据类型:, climate_data.dtype) # 一次性计算所有地区的产量 weights np.array([0.3, 0.2, 0.5]) yields climate_data weights # 矩阵乘法 print(各地区产量:, yields) # 数组索引和切片 print(第一个地区数据:, climate_data[0]) # 第一行 print(所有地区温度:, climate_data[:, 0]) # 第一列 print(前两个地区的前两个指标:, climate_data[:2, :2])3.4 文件读写实战从CSV文件读取数据并处理# 从网络下载示例数据 import urllib.request urllib.request.urlretrieve( https://hub.jovian.ml/wp-content/uploads/2020/08/climate.csv, climate.txt) # 读取CSV文件 climate_data np.genfromtxt(climate.txt, delimiter,, skip_header1) print(f数据形状: {climate_data.shape}) print(前5行数据:) print(climate_data[:5]) # 计算产量并保存结果 yields climate_data np.array([0.3, 0.2, 0.5]) climate_results np.concatenate((climate_data, yields.reshape(10000, 1)), axis1) # 保存结果到文件 np.savetxt(climate_results.txt, climate_results, fmt%.2f, delimiter,, headertemperature,rainfall,humidity,yield_apples, comments) print(结果已保存到climate_results.txt)4. Pandas表格数据处理4.1 数据读取与探索Pandas的DataFrame是处理表格数据的利器import pandas as pd from urllib.request import urlretrieve # 下载疫情数据 urlretrieve(https://hub.jovian.ml/wp-content/uploads/2020/09/italy-covid-daywise.csv, italy-covid-daywise.csv) # 读取CSV文件 covid_df pd.read_csv(italy-covid-daywise.csv) # 数据概览 print(数据形状:, covid_df.shape) print(\n前5行数据:) print(covid_df.head()) print(\n数据信息:) covid_df.info() print(\n数值列统计:) print(covid_df.describe())4.2 数据检索与操作多种方式访问和操作数据# 列数据访问 cases_series covid_df[new_cases] print(病例数列类型:, type(cases_series)) print(8月30日病例数:, covid_df.at[243, new_cases]) # 行数据访问 august_30 covid_df.loc[243] print(8月30日所有数据:) print(august_30) # 数据切片 print(8月数据:) print(covid_df.loc[108:113]) # 创建数据子集 cases_df covid_df[[date, new_cases]] print(病例数据子集形状:, cases_df.shape)4.3 数据分析与统计回答实际业务问题# 总病例和死亡数 total_cases covid_df.new_cases.sum() total_deaths covid_df.new_deaths.sum() print(f总病例数: {int(total_cases)}) print(f总死亡数: {int(total_deaths)}) # 死亡率计算 death_rate total_deaths / total_cases print(f死亡率: {death_rate*100:.2f}%) # 测试数据统计 initial_tests 935310 total_tests initial_tests covid_df.new_tests.sum() positive_rate total_cases / total_tests print(f阳性率: {positive_rate*100:.2f}%)4.4 数据查询与排序筛选和排序特定条件的数据# 查询高病例天数 high_cases_df covid_df[covid_df.new_cases 1000] print(f病例数超过1000的天数: {len(high_cases_df)}) # 复杂查询 positive_rate total_cases / total_tests high_ratio_df covid_df[covid_df.new_cases / covid_df.new_tests positive_rate] print(f阳性率高于平均的天数: {len(high_ratio_df)}) # 数据排序 print(病例数最高的10天:) print(covid_df.sort_values(new_cases, ascendingFalse).head(10)) print(死亡数最高的10天:) print(covid_df.sort_values(new_deaths, ascendingFalse).head(10))4.5 时间序列处理处理日期数据是常见需求# 转换日期格式 covid_df[date] pd.to_datetime(covid_df.date) # 提取时间成分 covid_df[year] pd.DatetimeIndex(covid_df.date).year covid_df[month] pd.DatetimeIndex(covid_df.date).month covid_df[day] pd.DatetimeIndex(covid_df.date).day covid_df[weekday] pd.DatetimeIndex(covid_df.date).weekday # 月度分析 may_totals covid_df[covid_df.month 5][[new_cases, new_deaths, new_tests]].sum() print(5月份统计:) print(may_totals) # 周日vs平日对比 weekday_avg covid_df.new_cases.mean() sunday_avg covid_df[covid_df.weekday 6].new_cases.mean() print(f平日平均病例: {weekday_avg:.1f}) print(f周日平均病例: {sunday_avg:.1f})4.6 数据聚合与合并分组统计和多数据源合并# 月度聚合 covid_month_df covid_df.groupby(month)[[new_cases, new_deaths, new_tests]].sum() print(月度聚合数据:) print(covid_month_df) # 累积计算 covid_df[total_cases] covid_df.new_cases.cumsum() covid_df[total_deaths] covid_df.new_deaths.cumsum() covid_df[total_tests] covid_df.new_tests.cumsum() initial_tests # 多数据源合并 covid_df[location] Italy # 下载国家数据 urlretrieve(https://gist.githubusercontent.com/aakashns/8684589ef4f266116cdce023377fc9c8/raw/99ce3826b2a9d1e6d0bde7e9e559fc8b6e9ac88b/locations.csv, locations.csv) locations_df pd.read_csv(locations.csv) italy_info locations_df[locations_df.location Italy] # 数据合并 merged_df covid_df.merge(locations_df, onlocation) # 计算人均指标 merged_df[cases_per_million] merged_df.total_cases * 1e6 / merged_df.population merged_df[deaths_per_million] merged_df.total_deaths * 1e6 / merged_df.population merged_df[tests_per_million] merged_df.total_tests * 1e6 / merged_df.population print(合并后数据形状:, merged_df.shape)5. Matplotlib数据可视化5.1 基础折线图可视化数据趋势import matplotlib.pyplot as plt import seaborn as sns # 设置中文字体和图形样式 plt.rcParams[font.sans-serif] [SimHei] # 用来正常显示中文标签 plt.rcParams[axes.unicode_minus] False # 用来正常显示负号 sns.set_style(whitegrid) # 苹果产量数据 years [2010, 2011, 2012, 2013, 2014, 2015] yield_apples [0.895, 0.91, 0.919, 0.926, 0.929, 0.931] plt.figure(figsize(10, 6)) plt.plot(years, yield_apples, markero, linewidth2, markersize8) plt.xlabel(年份) plt.ylabel(产量 (吨/公顷)) plt.title(Kanto地区苹果产量变化) plt.grid(True, alpha0.3) plt.show()5.2 多线对比图比较多个数据系列years range(2000, 2012) apples [0.895, 0.91, 0.919, 0.926, 0.929, 0.931, 0.934, 0.936, 0.937, 0.9375, 0.9372, 0.939] oranges [0.962, 0.941, 0.930, 0.923, 0.918, 0.908, 0.907, 0.904, 0.901, 0.898, 0.9, 0.896] plt.figure(figsize(12, 6)) plt.plot(years, apples, s-b, label苹果, linewidth2, markersize8) plt.plot(years, oranges, o--r, label橘子, linewidth2, markersize8) plt.xlabel(年份) plt.ylabel(产量 (吨/公顷)) plt.title(Kanto地区作物产量对比) plt.legend() plt.grid(True, alpha0.3) plt.show()5.3 散点图分析关系分析两个变量之间的关系# 鸢尾花数据集分析 flowers_df sns.load_dataset(iris) plt.figure(figsize(10, 6)) sns.scatterplot(xsepal_length, ysepal_width, huespecies, s100, dataflowers_df) plt.title(鸢尾花萼片尺寸关系) plt.xlabel(萼片长度 (cm)) plt.ylabel(萼片宽度 (cm)) plt.show()5.4 直方图分析分布查看数据分布情况plt.figure(figsize(12, 5)) plt.subplot(1, 2, 1) plt.hist(flowers_df.sepal_width, bins15, alpha0.7, colorskyblue) plt.xlabel(萼片宽度 (cm)) plt.ylabel(频数) plt.title(萼片宽度分布) plt.subplot(1, 2, 2) # 按品种分别显示 setosa_df flowers_df[flowers_df.species setosa] versicolor_df flowers_df[flowers_df.species versicolor] virginica_df flowers_df[flowers_df.species virginica] plt.hist([setosa_df.sepal_width, versicolor_df.sepal_width, virginica_df.sepal_width], binsnp.arange(2, 5, 0.25), label[Setosa, Versicolor, Virginica], alpha0.7) plt.xlabel(萼片宽度 (cm)) plt.ylabel(频数) plt.title(各品种萼片宽度分布) plt.legend() plt.tight_layout() plt.show()5.5 疫情数据可视化实战综合应用所有技术# 准备数据 result_df merged_df[[date, new_cases, total_cases, new_deaths, total_deaths]] result_df.set_index(date, inplaceTrue) # 创建多子图 fig, axes plt.subplots(2, 2, figsize(15, 10)) # 每日新增病例 axes[0,0].plot(result_df.new_cases, linewidth1) axes[0,0].set_title(意大利每日新增病例) axes[0,0].set_ylabel(病例数) axes[0,0].grid(True, alpha0.3) # 累计病例 axes[0,1].plot(result_df.total_cases, linewidth1) axes[0,1].set_title(意大利累计病例) axes[0,1].set_ylabel(病例数) axes[0,1].grid(True, alpha0.3) # 每日死亡数 axes[1,0].plot(result_df.new_deaths, linewidth1, colorred) axes[1,0].set_title(意大利每日死亡数) axes[1,0].set_ylabel(死亡数) axes[1,0].grid(True, alpha0.3) # 累计死亡数 axes[1,1].plot(result_df.total_deaths, linewidth1, colorred) axes[1,1].set_title(意大利累计死亡数) axes[1,1].set_ylabel(死亡数) axes[1,1].grid(True, alpha0.3) plt.tight_layout() plt.show()5.6 高级可视化技巧使用Seaborn创建更专业的图表# 热力图展示航班数据 flights_df sns.load_dataset(flights).pivot(month, year, passengers) plt.figure(figsize(12, 8)) sns.heatmap(flights_df, annotTrue, fmtd, cmapBlues) plt.title(月度航班乘客数热力图) plt.show() # 配对图分析多变量关系 plt.figure(figsize(12, 10)) sns.pairplot(flowers_df, huespecies, height2.5) plt.suptitle(鸢尾花多变量关系分析, y1.02) plt.show()6. 完整项目实战苹果产量预测系统6.1 项目概述综合运用所学知识构建一个完整的产量预测系统class CropYieldPredictor: def __init__(self): self.weights np.array([0.3, 0.2, 0.5]) # 温度、降雨、湿度权重 self.regions_data {} def load_data(self, filepath): 从文件加载气候数据 self.raw_data np.genfromtxt(filepath, delimiter,, skip_header1) return self.raw_data def predict_yield(self, climate_data): 预测产量 if len(climate_data.shape) 1: # 单个地区 return np.dot(climate_data, self.weights) else: # 多个地区 return climate_data self.weights def analyze_regions(self, climate_data, region_names): 分析多个地区 yields self.predict_yield(climate_data) results_df pd.DataFrame({ region: region_names, temperature: climate_data[:, 0], rainfall: climate_data[:, 1], humidity: climate_data[:, 2], predicted_yield: yields }) return results_df.sort_values(predicted_yield, ascendingFalse) def visualize_analysis(self, results_df): 可视化分析结果 fig, axes plt.subplots(2, 2, figsize(15, 10)) # 产量排名 axes[0,0].barh(results_df.region, results_df.predicted_yield, colorlightgreen) axes[0,0].set_title(各地区产量预测排名) axes[0,0].set_xlabel(预测产量 (吨/公顷)) # 气候指标散点图 scatter axes[0,1].scatter(results_df.temperature, results_df.rainfall, cresults_df.predicted_yield, s100, cmapviridis) axes[0,1].set_xlabel(温度) axes[0,1].set_ylabel(降雨量) axes[0,1].set_title(温度-降雨量-产量关系) plt.colorbar(scatter, axaxes[0,1]) # 产量分布 axes[1,0].hist(results_df.predicted_yield, bins10, alpha0.7, colororange) axes[1,0].set_xlabel(预测产量) axes[1,0].set_ylabel(地区数量) axes[1,0].set_title(产量分布) # 指标相关性热力图 corr_matrix results_df[[temperature, rainfall, humidity, predicted_yield]].corr() sns.heatmap(corr_matrix, annotTrue, cmapcoolwarm, center0, axaxes[1,1]) axes[1,1].set_title(指标相关性热力图) plt.tight_layout() plt.show() # 使用示例 predictor CropYieldPredictor() # 模拟数据 regions [Kanto, Johto, Hoenn, Sinnoh, Unova] climate_data np.array([[73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70]]) # 分析预测 results predictor.analyze_regions(climate_data, regions) print(产量预测结果:) print(results) # 可视化 predictor.visualize_analysis(results)7. 常见问题与解决方案7.1 安装问题排查问题现象可能原因解决方案ModuleNotFoundError库未安装或环境错误使用pip install正确安装检查Python环境导入警告或错误版本不兼容更新库版本pip install --upgrade package_name图形显示问题后端配置错误添加%matplotlib inlineJupyter或使用plt.show()7.2 数据处理常见错误# 处理缺失值示例 def handle_missing_data(df): 处理数据中的缺失值 print(缺失值统计:) print(df.isnull().sum()) # 多种处理策略 # 1. 删除缺失行 df_dropped df.dropna() # 2. 填充均值 df_filled_mean df.fillna(df.mean()) # 3. 向前填充 df_ffill df.fillna(methodffill) return df_dropped # 根据需求选择策略 # 数据类型转换 def convert_dtypes(df): 优化数据类型节省内存 # 转换数值列 for col in df.select_dtypes(include[float64]).columns: df[col] pd.to_numeric(df[col], downcastfloat) # 转换整数列 for col in df.select_dtypes(include[int64]).columns: df[col] pd.to_numeric(df[col], downcastinteger) return df7.3 可视化优化技巧def create_professional_chart(data, title): 创建专业级图表模板 plt.figure(figsize(10, 6)) # 使用seaborn样式 sns.set_style(whitegrid) sns.set_palette(husl) # 创建图表根据数据类型选择 if len(data.shape) 1: # 单变量数据 - 直方图 plt.hist(data, bins20, alpha0.7, edgecolorblack) plt.ylabel(频数) else: # 多变量数据 - 折线图 for i in range(data.shape[1]): plt.plot(data[:, i], labelfSeries {i1}) plt.legend() # 美化图表 plt.title(title, fontsize14, fontweightbold) plt.xlabel(X轴, fontsize12) plt.ylabel(Y轴, fontsize12) plt.grid(True, alpha0.3) # 添加边框 for spine in plt.gca().spines.values(): spine.set_linewidth(0.5) plt.tight_layout() return plt.gcf()8. 学习路径与进阶资源8.1 循序渐进学习计划第一周掌握Numpy数组操作和数学运算第二周学习Pandas数据读写和基本分析第三周实践数据清洗和转换技巧第四周掌握Matplotlib各种图表绘制第五周完成综合项目实战8.2 推荐练习数据集鸢尾花数据集分类问题泰坦尼克数据集二分类预测波士顿房价数据集回归问题COVID-19数据时间序列分析8.3 进阶学习方向统计分析学习Scipy进行统计检验机器学习掌握Scikit-learn构建预测模型大数据处理学习PySpark处理海量数据交互可视化学习Plotly创建交互图表这个教程涵盖了Python数据分析的核心技能栈从基础的环境搭建到完整的项目实战。重要的是多动手实践遇到问题查阅文档逐步建立自己的数据分析工作流。建议按照文章中的代码示例逐个运行理解每个函数的作用然后尝试应用到自己的数据集中。数据分析是实践性很强的技能只有通过实际项目才能真正掌握。