尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

Python数据分析三剑客实战:气象数据可视化与产量预测

Python数据分析三剑客实战:气象数据可视化与产量预测
📅 发布时间:2026/7/14 18:53:07

很多同学在入门数据分析时,常常被各种库和概念搞得晕头转向。本文将通过一个完整的气象数据分析项目,手把手带你掌握Python数据分析三剑客:Numpy、Pandas和Matplotlib,从零基础到能够独立完成数据分析项目。

1. 环境准备与工具安装

1.1 Python环境配置

首先确保你已安装Python 3.7或更高版本。推荐使用Anaconda发行版,它包含了数据分析所需的常用库。

# 检查Python版本 python --version # 安装必要的库 pip install numpy pandas matplotlib seaborn jupyter

1.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(f"NumPy版本: {np.__version__}") print(f"Pandas版本: {pd.__version__}") print(f"Matplotlib版本: {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(f"NumPy计算结果: {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(f"Python列表计算时间: {py_time:.4f}秒") print(f"NumPy数组计算时间: {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=',', header='temperature,rainfall,humidity', fmt='%d') # 从CSV文件读取数据 loaded_data = np.genfromtxt('sample_climate.csv', delimiter=',', skip_header=1) 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', ascending=False) 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', inplace=True) 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', freq='D') 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_type='apple'): """根据气象数据预测作物产量""" 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']), axis=1 ) weather_df['wheat_yield'] = weather_df.apply( lambda row: predict_yield(row['temperature'], row['rainfall'], row['humidity'], 'wheat'), axis=1 ) 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'], linewidth=1, alpha=0.7, color='red') plt.title('2023年每日温度变化', fontsize=14, fontweight='bold') plt.xlabel('日期') plt.ylabel('温度 (°C)') plt.grid(True, alpha=0.3) plt.tight_layout() plt.show()

5.2 多子图对比分析

# 创建多子图对比不同气象指标 fig, axes = plt.subplots(2, 2, figsize=(15, 10)) # 温度分布 axes[0,0].hist(weather_df['temperature'], bins=30, color='lightcoral', alpha=0.7) axes[0,0].set_title('温度分布直方图') axes[0,0].set_xlabel('温度 (°C)') axes[0,0].set_ylabel('频次') # 降雨量分布 axes[0,1].hist(weather_df['rainfall'], bins=30, color='lightblue', alpha=0.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'], alpha=0.6, color='green') 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, color='orange', alpha=0.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(kind='bar', color=['lightgreen', 'coral', 'gold', 'lightblue']) plt.title('季节性苹果产量预测') plt.ylabel('预测产量') # 湿度与产量关系 plt.subplot(2, 2, 4) plt.scatter(weather_df['humidity'], weather_df['apple_yield'], alpha=0.5, c=weather_df['temperature'], cmap='viridis') 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, annot=True, cmap='coolwarm', center=0, square=True, fmt='.3f') plt.title('气象变量与产量预测相关性热力图') plt.tight_layout() plt.show()

6.2 时间序列分析

# 移动平均平滑处理 weather_df['temp_7d_avg'] = weather_df['temperature'].rolling(window=7).mean() weather_df['yield_7d_avg'] = weather_df['apple_yield'].rolling(window=7).mean() # 时间序列趋势分析 plt.figure(figsize=(14, 10)) # 原始温度与移动平均 plt.subplot(2, 2, 1) plt.plot(weather_df['date'], weather_df['temperature'], alpha=0.3, label='每日温度') plt.plot(weather_df['date'], weather_df['temp_7d_avg'], linewidth=2, label='7日移动平均', color='red') plt.title('温度时间序列与趋势') plt.xlabel('日期') plt.ylabel('温度 (°C)') plt.legend() plt.grid(True, alpha=0.3) # 产量预测趋势 plt.subplot(2, 2, 2) plt.plot(weather_df['date'], weather_df['apple_yield'], alpha=0.3, label='每日预测') plt.plot(weather_df['date'], weather_df['yield_7d_avg'], linewidth=2, label='7日移动平均', color='green') plt.title('苹果产量预测趋势') plt.xlabel('日期') plt.ylabel('预测产量') plt.legend() plt.grid(True, alpha=0.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'], color='blue', alpha=0.7) plt.title('月度降雨量总和') plt.xlabel('月份') plt.ylabel('降雨量 (mm)') plt.subplot(2, 2, 4) plt.plot(monthly_analysis['month'], monthly_analysis['apple_yield'], marker='o', linewidth=2, color='orange') plt.title('月度平均产量预测') plt.xlabel('月份') plt.ylabel('平均预测产量') plt.grid(True, alpha=0.3) plt.tight_layout() plt.show()

6.3 异常检测与处理

# 检测温度异常值 def detect_outliers_zscore(data, threshold=3): """使用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'], alpha=0.6, label='正常值', color='blue') plt.scatter(outlier_data['date'], outlier_data['temperature'], color='red', label='异常值', s=100, edgecolors='black') plt.title('温度异常值检测') plt.xlabel('日期') plt.ylabel('温度 (°C)') plt.legend() plt.grid(True, alpha=0.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:idx+1, 'temperature'].mean() weather_df_cleaned.loc[idx, 'temperature'] = prev_val print("异常值处理完成!")

7. 项目总结与最佳实践

7.1 完整数据分析流程回顾

通过本项目,我们完成了从数据准备到可视化分析的完整流程:

  1. 数据准备:创建模拟气象数据集,处理时间序列
  2. 数据清洗:处理缺失值和异常值
  3. 特征工程:添加季节、月度等时间特征
  4. 模型构建:建立产量预测模型
  5. 数据分析:进行统计分析和相关性研究
  6. 可视化:使用多种图表展示分析结果

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], bins=30, alpha=0.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 进一步学习建议

  1. 扩展学习:

    • 学习使用Seaborn进行高级统计可视化
    • 掌握Scikit-learn进行机器学习预测
    • 了解Plotly创建交互式图表
  2. 实战项目建议:

    • 尝试使用真实气象数据(如国家气象局开放数据)
    • 探索不同作物的生长模型
    • 加入更多影响因素(土壤数据、病虫害等)
  3. 性能优化技巧:

    • 对于大数据集,学习使用Dask替代Pandas
    • 掌握NumPy的向量化操作避免循环
    • 学习使用内存映射文件处理超大数据

这个完整的教程涵盖了Python数据分析的核心技能链,从基础的NumPy数组操作到复杂的Pandas数据分析,再到丰富的Matplotlib可视化。通过这个气象数据分析项目,你不仅学会了工具的使用,更重要的是掌握了数据分析的完整思维流程。

相关新闻

  • 2026年7月株洲天元黄金回收实测:正规靠谱门店推荐 本地变现不踩坑攻略 - 生活测评小能手
  • A3910与STM32G474RE电机控制方案详解
  • NSGA-II实战:从算法原理到Python代码实现与工业应用

最新新闻

  • 大模型智能体架构设计与多智能体系统实践
  • 吸水强厨房纸哪家口碑好:联盛森宝广受认可 - MXyuyu
  • 思源宋体CN:7种字重开源中文字体,彻底解决中文排版难题
  • 新手黄金回收别乱选,天津正规门店交易透明无猫腻 - 小蝶回收测评
  • AI生成文献综述会被发现吗?2026年真相与正确用法
  • 武汉百达翡丽回收价格查询与靠谱平台实测排行(2026年7月最新数据) - 天价名表回收平台

日新闻

  • AWS SSM安全运维实践:零公网暴露的合规远程开发方案
  • Tableau 2024.1 图表选择指南:5种业务场景与最佳图表类型匹配
  • dsPIC33FJ与CMT-8540S-SMT在嵌入式音频处理中的高效应用

周新闻

  • IX9104 PCIe5.0 高速交换芯片@ACP#完整规格 + 应用场景总结
  • Unity游戏集成Coze智能体:实现NPC智能对话与知识库联动
  • SAP EPIC 建行回单查询:从标准类CL_EPIC_EXAMPLE_CN_CCB_GHTD到Z类的5处关键修改

月新闻

  • 2026年6月公司网站搭建最新热门渠道测评:四大低成本/零代码平台对比+避坑
  • 【Linux】Linux arm 编译QT程序,出现expected “}“报错
  • 【MATLAB例程】四基站二维AOA定位与距离辅助增强对比仿真。基于角度观测和测距修正的固定目标平面定位精度分析

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号