
很多同学在入门数据分析时常常被各种库和概念搞得晕头转向。本文将通过一个完整的气象数据分析项目手把手带你掌握Python数据分析三剑客Numpy、Pandas和Matplotlib从零基础到能够独立完成数据分析项目。1. 环境准备与工具安装1.1 Python环境配置首先确保你已安装Python 3.7或更高版本。推荐使用Anaconda发行版它包含了数据分析所需的常用库。# 检查Python版本 python --version # 安装必要的库 pip install numpy pandas matplotlib seaborn jupyter1.2 Jupyter Notebook使用Jupyter Notebook是数据分析的利器让我们可以交互式地执行代码和查看结果。# 启动Jupyter Notebook jupyter notebook # 在Notebook中测试环境 import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns print(所有库导入成功) print(fNumPy版本: {np.__version__}) print(fPandas版本: {pd.__version__}) print(fMatplotlib版本: {plt.__version__})2. NumPy数值计算基础2.1 从Python列表到NumPy数组NumPy是Python科学计算的基础库提供了高性能的多维数组对象。# 传统Python列表计算苹果产量 kanto_temp 73 kanto_rainfall 67 kanto_humidity 43 weights [0.3, 0.2, 0.5] # 手动计算 kanto_yield kanto_temp * weights[0] kanto_rainfall * weights[1] kanto_humidity * weights[2] print(f手动计算结果: {kanto_yield}) # 使用NumPy数组计算 kanto np.array([73, 67, 43]) weights_np np.array([0.3, 0.2, 0.5]) kanto_yield_np np.dot(kanto, weights_np) print(fNumPy计算结果: {kanto_yield_np})2.2 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_py sum(x*y for x,y in zip(arr1, arr2)) 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}倍)2.3 多维数组操作# 创建二维数组矩阵 climate_data np.array([ [73, 67, 43], # 地区1: 温度,降雨量,湿度 [91, 88, 64], # 地区2 [87, 134, 58], # 地区3 [102, 43, 37], # 地区4 [69, 96, 70] # 地区5 ]) print(气候数据矩阵:) print(climate_data) print(f数组形状: {climate_data.shape}) print(f数组维度: {climate_data.ndim}) # 矩阵乘法计算所有地区产量 weights np.array([0.3, 0.2, 0.5]) yields climate_data weights # 矩阵乘法 print(f各地区产量预测: {yields})2.4 文件读写操作# 生成示例气候数据 np.random.seed(42) sample_data np.random.randint(20, 100, size(100, 3)) # 保存到CSV文件 np.savetxt(sample_climate.csv, sample_data, delimiter,, headertemperature,rainfall,humidity, fmt%d) # 从CSV文件读取数据 loaded_data np.genfromtxt(sample_climate.csv, delimiter,, skip_header1) print(从文件加载的数据:) print(loaded_data[:5]) # 显示前5行3. Pandas数据分析实战3.1 DataFrame基础操作Pandas提供了DataFrame这一强大的数据结构专门用于处理表格数据。# 创建示例数据 data { date: [2023-01-01, 2023-01-02, 2023-01-03, 2023-01-04], temperature: [25, 28, 22, 30], rainfall: [10, 5, 15, 2], humidity: [60, 55, 70, 45] } df pd.DataFrame(data) print(原始DataFrame:) print(df) print(f数据形状: {df.shape}) # 基本信息查看 print(\n数据基本信息:) print(df.info()) print(\n数值列统计信息:) print(df.describe())3.2 数据筛选与查询# 单列数据访问 temperatures df[temperature] print(温度数据:) print(temperatures) # 条件筛选 high_temp_days df[df[temperature] 25] print(\n高温天气记录:) print(high_temp_days) # 多条件查询 rainy_high_temp df[(df[rainfall] 5) (df[temperature] 20)] print(\n降雨且温度适宜的记录:) print(rainy_high_temp) # 排序操作 sorted_by_temp df.sort_values(temperature, ascendingFalse) print(\n按温度降序排列:) print(sorted_by_temp)3.3 数据处理与清洗# 处理缺失值示例 df_with_missing df.copy() df_with_missing.loc[2, rainfall] np.nan # 模拟缺失值 print(包含缺失值的数据:) print(df_with_missing) # 填充缺失值 df_filled df_with_missing.fillna({rainfall: df_with_missing[rainfall].mean()}) print(\n填充缺失值后:) print(df_filled) # 添加新列 df[yield_prediction] df[temperature] * 0.3 df[rainfall] * 0.2 df[humidity] * 0.5 print(\n添加产量预测列:) print(df)3.4 时间序列处理# 转换日期格式 df[date] pd.to_datetime(df[date]) df.set_index(date, inplaceTrue) print(设置日期索引后的数据:) print(df) # 时间序列操作 df[month] df.index.month df[day_of_week] df.index.dayofweek print(\n添加时间特征后:) print(df) # 按月份分组统计 monthly_stats df.groupby(month).agg({ temperature: [mean, max, min], rainfall: sum }) print(\n月度统计:) print(monthly_stats)4. 真实项目气象数据分析4.1 数据准备与探索让我们使用一个真实的气象数据集进行分析。# 创建更完整的气象数据集 np.random.seed(123) dates pd.date_range(2023-01-01, 2023-12-31, freqD) n_days len(dates) # 生成模拟气象数据 weather_data { date: dates, temperature: np.random.normal(25, 5, n_days), # 平均25度标准差5 rainfall: np.random.exponential(2, n_days), # 降雨量 humidity: np.random.normal(60, 10, n_days), # 湿度 wind_speed: np.random.gamma(2, 2, n_days) # 风速 } weather_df pd.DataFrame(weather_data) weather_df[temperature] weather_df[temperature].round(1) weather_df[rainfall] weather_df[rainfall].round(1) weather_df[humidity] weather_df[humidity].round(1) weather_df[wind_speed] weather_df[wind_speed].round(1) print(气象数据概览:) print(weather_df.head()) print(f\n数据规模: {weather_df.shape}) # 添加季节信息 def get_season(month): if month in [12, 1, 2]: return 冬季 elif month in [3, 4, 5]: return 春季 elif month in [6, 7, 8]: return 夏季 else: return 秋季 weather_df[month] weather_df[date].dt.month weather_df[season] weather_df[month].apply(get_season)4.2 数据聚合与分析# 季节性分析 seasonal_analysis weather_df.groupby(season).agg({ temperature: [mean, std, max, min], rainfall: [sum, mean], humidity: mean }).round(2) print(季节性气象分析:) print(seasonal_analysis) # 月度趋势分析 monthly_trend weather_df.groupby(month).agg({ temperature: mean, rainfall: sum, humidity: mean }).round(2) print(\n月度趋势:) print(monthly_trend)4.3 农业产量预测模型# 基于气象数据的产量预测模型 def predict_yield(temp, rain, humidity, crop_typeapple): 根据气象数据预测作物产量 if crop_type apple: weights np.array([0.3, 0.2, 0.5]) elif crop_type wheat: weights np.array([0.4, 0.3, 0.3]) else: weights np.array([0.35, 0.25, 0.4]) features np.array([temp, rain, humidity]) return np.dot(features, weights) # 应用预测模型 weather_df[apple_yield] weather_df.apply( lambda row: predict_yield(row[temperature], row[rainfall], row[humidity]), axis1 ) weather_df[wheat_yield] weather_df.apply( lambda row: predict_yield(row[temperature], row[rainfall], row[humidity], wheat), axis1 ) print(添加产量预测后的数据:) print(weather_df[[date, temperature, rainfall, apple_yield, wheat_yield]].head()) # 最佳种植时间分析 best_apple_days weather_df.nlargest(10, apple_yield)[[date, apple_yield, temperature, rainfall]] print(\n苹果最佳种植时间:) print(best_apple_days)5. Matplotlib数据可视化5.1 基础图表绘制# 设置中文字体解决中文显示问题 plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False # 温度变化折线图 plt.figure(figsize(12, 6)) plt.plot(weather_df[date], weather_df[temperature], linewidth1, alpha0.7, colorred) plt.title(2023年每日温度变化, fontsize14, fontweightbold) plt.xlabel(日期) plt.ylabel(温度 (°C)) plt.grid(True, alpha0.3) plt.tight_layout() plt.show()5.2 多子图对比分析# 创建多子图对比不同气象指标 fig, axes plt.subplots(2, 2, figsize(15, 10)) # 温度分布 axes[0,0].hist(weather_df[temperature], bins30, colorlightcoral, alpha0.7) axes[0,0].set_title(温度分布直方图) axes[0,0].set_xlabel(温度 (°C)) axes[0,0].set_ylabel(频次) # 降雨量分布 axes[0,1].hist(weather_df[rainfall], bins30, colorlightblue, alpha0.7) axes[0,1].set_title(降雨量分布) axes[0,1].set_xlabel(降雨量 (mm)) axes[0,1].set_ylabel(频次) # 温度-降雨量散点图 axes[1,0].scatter(weather_df[temperature], weather_df[rainfall], alpha0.6, colorgreen) axes[1,0].set_title(温度 vs 降雨量) axes[1,0].set_xlabel(温度 (°C)) axes[1,0].set_ylabel(降雨量 (mm)) # 月度平均温度 monthly_avg_temp weather_df.groupby(month)[temperature].mean() axes[1,1].bar(monthly_avg_temp.index, monthly_avg_temp.values, colororange, alpha0.7) axes[1,1].set_title(月度平均温度) axes[1,1].set_xlabel(月份) axes[1,1].set_ylabel(平均温度 (°C)) plt.tight_layout() plt.show()5.3 季节性分析可视化# 季节性箱线图分析 plt.figure(figsize(12, 8)) # 温度季节性分布 plt.subplot(2, 2, 1) seasonal_temp_data [weather_df[weather_df[season] season][temperature] for season in [春季, 夏季, 秋季, 冬季]] plt.boxplot(seasonal_temp_data, labels[春季, 夏季, 秋季, 冬季]) plt.title(季节性温度分布) plt.ylabel(温度 (°C)) # 降雨量季节性分布 plt.subplot(2, 2, 2) seasonal_rain_data [weather_df[weather_df[season] season][rainfall] for season in [春季, 夏季, 秋季, 冬季]] plt.boxplot(seasonal_rain_data, labels[春季, 夏季, 秋季, 冬季]) plt.title(季节性降雨量分布) plt.ylabel(降雨量 (mm)) # 产量预测季节性分析 plt.subplot(2, 2, 3) seasonal_yield weather_df.groupby(season)[apple_yield].mean() seasonal_yield.plot(kindbar, color[lightgreen, coral, gold, lightblue]) plt.title(季节性苹果产量预测) plt.ylabel(预测产量) # 湿度与产量关系 plt.subplot(2, 2, 4) plt.scatter(weather_df[humidity], weather_df[apple_yield], alpha0.5, cweather_df[temperature], cmapviridis) plt.colorbar(label温度 (°C)) plt.xlabel(湿度 (%)) plt.ylabel(苹果预测产量) plt.title(湿度与产量关系按温度着色) plt.tight_layout() plt.show()6. 高级数据分析技巧6.1 相关性分析# 计算变量间的相关系数 correlation_matrix weather_df[[temperature, rainfall, humidity, wind_speed, apple_yield, wheat_yield]].corr() print(变量间相关系数矩阵:) print(correlation_matrix.round(3)) # 热力图可视化相关性 plt.figure(figsize(10, 8)) sns.heatmap(correlation_matrix, annotTrue, cmapcoolwarm, center0, squareTrue, fmt.3f) plt.title(气象变量与产量预测相关性热力图) plt.tight_layout() plt.show()6.2 时间序列分析# 移动平均平滑处理 weather_df[temp_7d_avg] weather_df[temperature].rolling(window7).mean() weather_df[yield_7d_avg] weather_df[apple_yield].rolling(window7).mean() # 时间序列趋势分析 plt.figure(figsize(14, 10)) # 原始温度与移动平均 plt.subplot(2, 2, 1) plt.plot(weather_df[date], weather_df[temperature], alpha0.3, label每日温度) plt.plot(weather_df[date], weather_df[temp_7d_avg], linewidth2, label7日移动平均, colorred) plt.title(温度时间序列与趋势) plt.xlabel(日期) plt.ylabel(温度 (°C)) plt.legend() plt.grid(True, alpha0.3) # 产量预测趋势 plt.subplot(2, 2, 2) plt.plot(weather_df[date], weather_df[apple_yield], alpha0.3, label每日预测) plt.plot(weather_df[date], weather_df[yield_7d_avg], linewidth2, label7日移动平均, colorgreen) plt.title(苹果产量预测趋势) plt.xlabel(日期) plt.ylabel(预测产量) plt.legend() plt.grid(True, alpha0.3) # 月度聚合分析 monthly_analysis weather_df.groupby(month).agg({ temperature: mean, rainfall: sum, apple_yield: mean }).reset_index() plt.subplot(2, 2, 3) plt.bar(monthly_analysis[month], monthly_analysis[rainfall], colorblue, alpha0.7) plt.title(月度降雨量总和) plt.xlabel(月份) plt.ylabel(降雨量 (mm)) plt.subplot(2, 2, 4) plt.plot(monthly_analysis[month], monthly_analysis[apple_yield], markero, linewidth2, colororange) plt.title(月度平均产量预测) plt.xlabel(月份) plt.ylabel(平均预测产量) plt.grid(True, alpha0.3) plt.tight_layout() plt.show()6.3 异常检测与处理# 检测温度异常值 def detect_outliers_zscore(data, threshold3): 使用Z-score方法检测异常值 z_scores np.abs((data - data.mean()) / data.std()) return z_scores threshold # 应用异常检测 temp_outliers detect_outliers_zscore(weather_df[temperature]) print(f检测到温度异常值数量: {temp_outliers.sum()}) # 可视化异常值 plt.figure(figsize(12, 6)) normal_data weather_df[~temp_outliers] outlier_data weather_df[temp_outliers] plt.scatter(normal_data[date], normal_data[temperature], alpha0.6, label正常值, colorblue) plt.scatter(outlier_data[date], outlier_data[temperature], colorred, label异常值, s100, edgecolorsblack) plt.title(温度异常值检测) plt.xlabel(日期) plt.ylabel(温度 (°C)) plt.legend() plt.grid(True, alpha0.3) plt.show() # 处理异常值使用移动平均填充 weather_df_cleaned weather_df.copy() if temp_outliers.any(): # 使用前后值的平均值填充异常值 for idx in outlier_data.index: prev_val weather_df_cleaned.loc[idx-1:idx1, temperature].mean() weather_df_cleaned.loc[idx, temperature] prev_val print(异常值处理完成)7. 项目总结与最佳实践7.1 完整数据分析流程回顾通过本项目我们完成了从数据准备到可视化分析的完整流程数据准备创建模拟气象数据集处理时间序列数据清洗处理缺失值和异常值特征工程添加季节、月度等时间特征模型构建建立产量预测模型数据分析进行统计分析和相关性研究可视化使用多种图表展示分析结果7.2 数据分析最佳实践# 数据分析流水线示例 def data_analysis_pipeline(dataframe): 完整的数据分析流水线 # 1. 数据质量检查 print( 数据质量检查 ) print(f数据形状: {dataframe.shape}) print(f缺失值统计:) print(dataframe.isnull().sum()) # 2. 基本统计信息 print(\n 基本统计信息 ) print(dataframe.describe()) # 3. 数据可视化概览 numerical_cols dataframe.select_dtypes(include[np.number]).columns plt.figure(figsize(15, 10)) for i, col in enumerate(numerical_cols[:4], 1): plt.subplot(2, 2, i) plt.hist(dataframe[col], bins30, alpha0.7) plt.title(f{col}分布) plt.xlabel(col) plt.ylabel(频次) plt.tight_layout() plt.show() # 4. 相关性分析 print(\n 变量相关性分析 ) corr_matrix dataframe[numerical_cols].corr() print(corr_matrix.round(3)) return corr_matrix # 应用分析流水线 correlation_result data_analysis_pipeline(weather_df)7.3 进一步学习建议扩展学习学习使用Seaborn进行高级统计可视化掌握Scikit-learn进行机器学习预测了解Plotly创建交互式图表实战项目建议尝试使用真实气象数据如国家气象局开放数据探索不同作物的生长模型加入更多影响因素土壤数据、病虫害等性能优化技巧对于大数据集学习使用Dask替代Pandas掌握NumPy的向量化操作避免循环学习使用内存映射文件处理超大数据这个完整的教程涵盖了Python数据分析的核心技能链从基础的NumPy数组操作到复杂的Pandas数据分析再到丰富的Matplotlib可视化。通过这个气象数据分析项目你不仅学会了工具的使用更重要的是掌握了数据分析的完整思维流程。