请编写代码(建议直接输出代码),完成对六个数据集的读取、预处理、整理到d… · The Chat Archive
Explore / Programming 请编写代码(建议直接输出代码),完成对六个数据集的读取、预处理、整理到dataframe(六个数据集都放到一个dataframe里,并导出为utf8的csv).… Save Share Download ▾ Report请编写代码(建议直接输出代码),完成对六个数据集的读取、预处理、整理到dataframe(六个数据集都放到一个dataframe里,并导出为utf8的csv).
数据集1-4有可运行的参考,并且按照顺序参考代码附后,5,6的数据集为网格式,类似数据集1的第二种处理。
要求
1、按年为粒度,但是要包含经纬度信息,可以进行0.01的网格采样以减少数量
2、气温、降水分别取每年的日最大值
3、土地利用选择采样点占比最大的(是个离散的类型变量而不是连续的尺度)
4、高程(海拔)使用第二种Albers的,包括海拔、坡度、坡向三列
六个数据集的基本信息如下:
中国数字高程图(1km)文件位置与缺值处理方式,参考后面代码(有两种)
数据集描述: 该数据集包含中国的数字高程信息,分辨率为1公里,采用两种不同的坐标系。
文件格式: GeoTIFF
路径: 解压后 Albers_105 文件夹为正轴割圆锥等面积投影数据,Geo/TIFF 文件夹下为WGS84地理坐标系数据。
主要文件: chinadem_geo.tif (地表每个像素代表海拔高度,单位为米)
中国0.1°近地表气温数据集(1979-2018年)文件位置与处理方式,参考后面代码
数据集描述: 包含1979-2018年每日中国近地表气温的分布,分辨率为0.1度。
文件格式: GeoTIFF
路径: 每一年数据为一个文件夹,文件夹中包含该年1月1日至12月31日每日气温的GeoTIFF文件。
主要文件: 每天的气温数据保存为GeoTIFF格式文件,文件夹以年份命名。
中国大陆0.25°逐日降水数据集(1961-2022年)文件位置与处理方式,参考后面代码
数据集描述: 包含1961-2022年每日中国大陆的降水分布,分辨率为0.25度。
文件格式: NetCDF
路径: 文件包含22645层图像,每一层对应从1961年1月1日至2022年12月31日每日的降水分布。
主要文件: NetCDF格式文件,包含每日降水量(单位为毫米)。
中国0.5°土地利用和覆盖变化数据集(1900-2019年)文件位置与处理方式,参考后面代码
数据集描述: 包含耕地、林地、草地、灌木丛、湿地五种土地覆被类型的时空分布,分辨率为0.5度。
文件格式: GeoTIFF
路径: 每一类覆被类型的数据文件命名为类型英文名加年份,如cropland_2019.tif。
主要文件: 不同覆被类型的数据按年份保存为多个GeoTIFF文件。
中国大陆1km逐年历史人口空间分布公里网格数据集(1990-2015年)文件位置如F:\HuaweiCup\DATA\data5\pop_output\pop1990\pop1990.tif
数据集描述: 包含1990-2015年每年中国大陆的人口分布,分辨率为1公里。
文件格式: GeoTIFF
路径: 每一年的数据存储在单独的文件夹中,图像以GeoTIFF格式保存。
主要文件: 每年的人口空间分布以GeoTIFF格式保存,文件夹以年份命名。
中国大陆1km逐年历史GDP空间分布公里网格数据集(1990-2015年)文件位置如F:\HuaweiCup\DATA\data6\GDP_output\gdp1990.tif
数据集描述: 包含1990-2015年中国大陆每年GDP的空间分布,分辨率为1公里。
文件格式: GeoTIFF
路径: 每一年的数据存储在单独的文件夹中,图像以GeoTIFF格式保存。
主要文件: 每年GDP的空间分布以GeoTIFF格式保存,文件夹以年份命名。
这些数据主要为GeoTIFF和NetCDF格式,Python可以使用rasterio库处理GeoTIFF数据,netCDF4库处理NetCDF数据。
%% [markdown]
## 高程 经纬度
%%
import os
import rasterio
import numpy as np
import matplotlib.pyplot as plt
设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
定义 Geo 文件夹下的 TIFF 文件路径
tif_file_path = r"F:\HuaweiCup\DATA\data1\Geo\TIFF\chinadem_geo.tif"
检查文件是否存在
if not os.path.exists(tif_file_path):
print(f"文件 {tif_file_path} 不存在,请检查路径。")
else:
# 打开并读取 TIFF 文件
with rasterio.open(tif_file_path) as src:
data = src.read(1) # 读取第一波段的数据(DEM 高程值)
bounds = src.bounds # 获取图像的边界
nodata = src.nodata # 获取缺失值标识符
resolution = src.res # 获取像素分辨率
width, height = src.width, src.height # 图像的宽度和高度
total_pixels = width * height # 计算总的数据点数(像素数)
Show full message · 1,142 lines Assistant2024-09-23 18:26 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language zh
Conversation date Sep 23, 2024
Added to archive Nov 16, 2026
ID 01m7h41vbj433y50d6qhgb4g0kSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 029185ec6621193af7043e5b38ad6875
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
# 如果有缺失值标识符,替换为 np.nan
if nodata is not None:
data = np.where(data == nodata, np.nan, data)
# 计算去除缺失值后的有效数据点总数
valid_pixels = np.count_nonzero(~np.isnan(data))
# 输出精度、规模等信息
print(f"文件:{tif_file_path}")
print(f"像素分辨率:{resolution[0]} x {resolution[1]} 度")
print(f"图像大小:宽 {width} 像素, 高 {height} 像素")
print(f"数据点总数(像素总数):{total_pixels}")
print(f"有效数据点总数(去除缺失值):{valid_pixels}")
print(f"地理范围:")
print(f" 经:{bounds.left}° 至 经:{bounds.right}°")
print(f" 纬:{bounds.bottom}° 至 纬:{bounds.top}°")
# 确定图像的显示范围(extent)以匹配地理坐标
extent = [bounds.left, bounds.right, bounds.bottom, bounds.top]
# 绘制数据,使用灰色调 cmap='YlOrRd' 显示海拔数据
plt.figure(figsize=(10, 8))
plt.imshow(data, cmap='YlOrRd', extent=extent)
plt.colorbar(label="海拔高度 (米)")
plt.title("中国数字高程图 (1km 分辨率)", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
plt.show()
%% [markdown]
## 高程 平面
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
定义 Albers_105 文件夹下的 TIFF 文件路径 base_dir = r"F:\HuaweiCup\DATA\data1\Albers_105\TIFF"
文件路径 dem_file = os.path.join(base_dir, "chdem_105.tif")
aspect_file = os.path.join(base_dir, "chdem_Aspect.tif")
slope_file = os.path.join(base_dir, "chdem_Slope.tif")
hillshade_file = os.path.join(base_dir, "chdem_hillshade.tif")
def read_and_display_tiff(file_path, title, cmap='terrain', label=''):
# 检查文件是否存在
if not os.path.exists(file_path):
print(f"文件 {file_path} 不存在,请检查路径。")
return
code Copy code
# 打开并读取 TIFF 文件
with rasterio.open(file_path) as src:
data = src.read(1) # 读取第一波段的数据
bounds = src.bounds # 获取图像的边界
nodata = src.nodata # 获取缺失值标识符
resolution = src.res # 获取像素分辨率
width, height = src.width, src.height # 图像的宽度和高度
total_pixels = width * height # 计算总的数据点数(像素数)
# 如果有缺失值标识符,替换为 np.nan
if nodata is not None:
data = np.where(data == nodata, np.nan, data)
# 计算去除缺失值后的有效数据点总数
valid_pixels = np.count_nonzero(~np.isnan(data))
# 输出精度、规模等信息
print(f"文件:{file_path}")
print(f"像素分辨率:{resolution[0]} x {resolution[1]} 单位")
print(f"图像大小:宽 {width} 像素, 高 {height} 像素")
print(f"数据点总数(像素总数):{total_pixels}")
print(f"有效数据点总数(去除缺失值):{valid_pixels}")
print(f"地理范围:")
print(f" 经:{bounds.left}° 至 经:{bounds.right}°")
print(f" 纬:{bounds.bottom}° 至 纬:{bounds.top}°")
# 确定图像的显示范围(extent)以匹配地理坐标
extent = [bounds.left, bounds.right, bounds.bottom, bounds.top]
# 绘制数据
plt.figure(figsize=(10, 8))
plt.imshow(data, cmap=cmap, extent=extent)
plt.colorbar(label=label)
plt.title(title, fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
plt.show()
读取并显示 DEM(高程)数据 read_and_display_tiff(dem_file, "中国高程图 (Albers 投影)",
cmap='terrain', label="海拔高度 (米)")
读取并显示坡向数据 read_and_display_tiff(aspect_file, "中国坡向图 (Albers 投影)",
cmap='twilight', label="坡向 (度)")
读取并显示坡度数据 read_and_display_tiff(slope_file, "中国坡度图 (Albers 投影)",
cmap='viridis', label="坡度 (度)")
读取并显示阴影图 read_and_display_tiff(hillshade_file, "中国阴影图 (Albers 投影)",
cmap='Greys', label="阴影")
%% [markdown]
## 气温
%% [markdown]
地区 城市 经度 (°E) 纬度 (°N)
华东 上海 121.4737 31.2304
华南 广州 113.2644 23.1291
华中 武汉 114.3055 30.5928
华北 北京 116.4074 39.9042
西南 成都 104.0665 30.5723
西北 西安 108.9398 34.3416
东北 沈阳 123.4315 41.8057
%% [markdown]
## 找有效值
%% from rasterio.transform import xy
import os
import rasterio
import numpy as np
import matplotlib.pyplot as plt
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
定义数据根目录 data_dir = r"F:\HuaweiCup\DATA\data2\day_avg"
获取年份目录列表 years = [d for d in os.listdir(
data_dir) if os.path.isdir(os.path.join(data_dir, d))]
初始化总有效数据点的计数 total_valid_pixels = 0
total_pixels = 0
遍历每个年份 for year in years:
year_dir = os.path.join(data_dir, year)
code Copy code
# 获取该年份下所有TIFF文件
tiff_files = [f for f in os.listdir(year_dir) if f.endswith('_avg.tif')]
# 遍历每个TIFF文件
for tiff_file in tiff_files:
tif_file_path = os.path.join(year_dir, tiff_file)
if os.path.exists(tif_file_path):
with rasterio.open(tif_file_path) as src:
data = src.read(1) # 读取第一波段数据
nodata = src.nodata # 获取缺失值标识符
width, height = src.width, src.height # 图像的宽度和高度
total_pixels_per_file = width * height # 计算每个文件的总数据点数
# 如果有缺失值标识符,替换为 np.nan
if nodata is not None:
data = np.where(data == nodata, np.nan, data)
# 计算去除缺失值后的有效数据点总数
valid_pixels_per_file = np.count_nonzero(~np.isnan(data))
# 累加总有效数据点数
total_valid_pixels += valid_pixels_per_file
total_pixels += total_pixels_per_file
输出所有日期的总数据点和有效数据点 print(f"所有日期数据点总数(像素总数):{total_pixels}")
print(f"所有日期有效数据点总数(去除缺失值):{total_valid_pixels}")
%% [markdown]
## 单日
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
定义数据根目录 data_dir = r"F:\HuaweiCup\DATA\data2\day_avg"
选择一个年份和一个日期 selected_year = "1979"
selected_day = "19790101"
构建 TIFF 文件路径 tif_file = os.path.join(
data_dir, f"{selected_year}_avg", f"{selected_day}_avg.tif")
检查文件是否存在 if not os.path.exists(tif_file):
print(f"文件 {tif_file} 不存在,请检查路径。")
else:
# 打开并读取 TIFF 文件
with rasterio.open(tif_file) as src:
data = src.read(1) # 读取第一波段的数据
bounds = src.bounds # 获取图像的边界
nodata = src.nodata # 获取缺失值标识符
resolution = src.res # 获取像素分辨率
width, height = src.width, src.height # 图像的宽度和高度
total_pixels = width * height # 计算总的数据点数(像素数)
code Copy code
# 如果有缺失值标识符,替换为 np.nan
if nodata is not None:
data = np.where(data == nodata, np.nan, data)
# 计算去除缺失值后的有效数据点总数
valid_pixels = np.count_nonzero(~np.isnan(data))
# 输出精度、规模等信息
print(f"文件:{tif_file}")
print(f"像素分辨率:{resolution[0]} x {resolution[1]} 度")
print(f"图像大小:宽 {width} 像素, 高 {height} 像素")
print(f"单个日期数据点总数(像素总数):{total_pixels}")
print(f"单个日期有效数据点总数(去除缺失值):{valid_pixels}")
print(f"地理范围:")
print(f" 经:{bounds.left}° 至 经:{bounds.right}°")
print(f" 纬:{bounds.bottom}° 至 纬:{bounds.top}°")
# 确定图像的显示范围(extent)以匹配地理坐标
extent = [bounds.left, bounds.right, bounds.bottom, bounds.top]
# 绘制数据
plt.figure(figsize=(10, 8))
plt.imshow(data, cmap='coolwarm', extent=extent)
plt.colorbar(label="气温 (°C)")
plt.title(f"{selected_day} 平均气温分布 (去除缺失值)", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
plt.show()
%% [markdown]
## 平均和方差
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
定义数据目录,直接指向包含所有 TIFF 文件的目录 data_dir = r"F:\HuaweiCup\DATA\data2\day_avg\1979_avg"
获取该目录下所有以 '_avg.tif' 结尾的文件,并按顺序排序 tif_files = sorted([os.path.join(data_dir, f)
for f in os.listdir(data_dir) if f.endswith('_avg.tif')])
初始化用于存储sum, sum of squares, and counts sum_data = None
sumsq_data = None
count_data = None
遍历每个 TIFF 文件 for tif_file in tif_files:
# 打开并读取 TIFF 文件
with rasterio.open(tif_file) as src:
data = src.read(1).astype(np.float64) # 读取第一波段的数据,确保为float64
nodata = src.nodata # 获取缺失值标识符
code Copy code
# 如果有缺失值标识符,替换为 np.nan
if nodata is not None:
data[data == nodata] = np.nan
# 初始化 sum_data, sumsq_data, count_data
if sum_data is None:
sum_data = np.zeros_like(data)
sumsq_data = np.zeros_like(data)
count_data = np.zeros_like(data)
# 创建有效数据的掩码
valid = ~np.isnan(data)
# 更新计数
count_data[valid] += 1
# 更新总和
sum_data[valid] += data[valid]
# 更新总和的平方
sumsq_data[valid] += data[valid] ** 2
计算平均气温 mean_data = np.full_like(sum_data, np.nan)
variance_data = np.full_like(sum_data, np.nan)
对于有效的数据点,计算平均值 valid = count_data > 0
mean_data[valid] = sum_data[valid] / count_data[valid]
对于至少有两个观测值的点,计算方差 valid_var = count_data > 1
variance_data[valid_var] = (sumsq_data[valid_var] - (sum_data[valid_var]
** 2) / count_data[valid_var]) / (count_data[valid_var] - 1)
检查方差和平均值的范围 print(f"平均气温最大值: {np.nanmax(mean_data)}, 最小值: {np.nanmin(mean_data)}")
print(f"气温方差最大值: {np.nanmax(variance_data)}, 最小值: {np.nanmin(variance_data)}")
使用第一个文件来获取地理信息 with rasterio.open(tif_files[0]) as src:
transform = src.transform
width = src.width
height = src.height
crs = src.crs
创建像素网格坐标 col_indices = np.arange(width)
row_indices = np.arange(height)
col_grid, row_grid = np.meshgrid(col_indices, row_indices)
使用仿射变换将像素坐标转换为地理坐标 lon_grid, lat_grid = xy(transform, row_grid, col_grid)
lon_grid = np.array(lon_grid)
lat_grid = np.array(lat_grid)
绘制平均气温图 plt.figure(figsize=(10, 6))
plt.contourf(lon_grid, lat_grid, mean_data, cmap='coolwarm', levels=20)
plt.colorbar(label='平均气温 (°C)')
plt.title("平均气温分布", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
plt.show()
绘制气温方差图 plt.figure(figsize=(10, 6))
plt.contourf(lon_grid, lat_grid, variance_data, cmap='coolwarm', levels=20)
plt.colorbar(label='气温方差 (°C^2)')
plt.title("气温方差分布", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
plt.show()
%% [markdown]
## 异常值发现
%%
定义数据根目录 data_dir = r"F:\HuaweiCup\DATA\data2\day_avg"
合理的温度范围 min_valid_temp = -100
max_valid_temp = 100
初始化全局最小值和最大值 global_min = float('inf')
global_max = float('-inf')
获取年份目录列表 years = [d for d in os.listdir(
data_dir) if os.path.isdir(os.path.join(data_dir, d))]
遍历每个年份 for year in years:
year_dir = os.path.join(data_dir, year)
# 获取该年份下所有TIFF文件
tiff_files = [f for f in os.listdir(year_dir) if f.endswith('_avg.tif')]
code Copy code
# 遍历每个TIFF文件
for tiff_file in tiff_files:
tif_file_path = os.path.join(year_dir, tiff_file)
if os.path.exists(tif_file_path):
with rasterio.open(tif_file_path) as src:
data = src.read(1) # 读取第一波段数据
nodata = src.nodata # 获取缺失值标识符
# 将缺失值替换为 NaN
cleaned_data = np.where(data == nodata, np.nan, data)
# 更新全局最大值和最小值
file_min = np.nanmin(cleaned_data)
file_max = np.nanmax(cleaned_data)
global_min = min(global_min, file_min)
global_max = max(global_max, file_max)
# 检查数据是否超出合理范围,并打印异常值
invalid_mask = (cleaned_data < min_valid_temp) | (
cleaned_data > max_valid_temp)
if np.any(invalid_mask):
# 找到异常值的坐标并立即打印
invalid_coords = np.argwhere(invalid_mask)
for row, col in invalid_coords:
print(
f"文件: {tiff_file}, 年份: {year}, 行: {row}, 列: {col}, 异常值: {cleaned_data[row, col]}")
输出全局最大值和最小值 print(f"全局最小值: {global_min}")
print(f"全局最大值: {global_max}")
%% [markdown]
## 变量读取
%% import matplotlib.pyplot as plt
import numpy as np
import netCDF4 as nc
from netCDF4 import num2date
定义NetCDF文件路径 file_path = r"F:\HuaweiCup\DATA\data3\CHM_PRE_0.25dg_19612022.nc\CHM_PRE_0.25dg_19612022.nc"
打开NetCDF文件 dataset = nc.Dataset(file_path, mode='r')
打印所有的变量名称 print("文件中的变量有:")
print(dataset.variables.keys())
查看文件中的变量 precipitation = dataset.variables['pre'][:] # 日降水数据
station_number = dataset.variables['station_number'][:] # 每年每个格点的站点数量
查看数据的时间维度和地理信息 time = dataset.variables['time'][:] # 时间维度
latitude = dataset.variables['latitude'][:] # 纬度
longitude = dataset.variables['longitude'][:] # 经度
获取单位信息(先检查属性是否存在) precipitation_units = dataset.variables['pre'].units if 'units' in dataset.variables['pre'].ncattrs(
) else '无单位'
station_number_units = dataset.variables['station_number'].units if 'units' in dataset.variables['station_number'].ncattrs(
) else '无单位'
将时间变量转换为日期 time_values = dataset.variables['time'][:]
time_units = dataset.variables['time'].units
使用 num2date 将时间转换为日期格式 dates = num2date(time_values, units=time_units)
打印前几个时间点对应的日期 print("前5个时间点对应的日期:", dates[:5])
打印基本信息 print(f"降水数据形状: {precipitation.shape}")
print(f"站点数量数据形状: {station_number.shape}")
print(f"纬度范围: {latitude.min()}°N 至 {latitude.max()}°N")
print(f"经度范围: {longitude.min()}°E 至 {longitude.max()}°E")
print(f"降水量单位: {precipitation_units}")
print(f"站点数量单位: {station_number_units}")
缺失值标识符
将缺失值标记为 NaN precipitation_cleaned = np.where(
precipitation == missing_value, np.nan, precipitation)
计算有效数据点总数(去除缺失值) valid_data_points = np.count_nonzero(~np.isnan(precipitation_cleaned))
打印有效数据点总数 print(f"有效数据点总数(去除缺失值): {valid_data_points}")
打印前20个时间点的降水数据(假设第一个维度是时间) print("\n前20个时间点的降水数据:")
print(precipitation[:20, :, :]) # 打印前20天的降水数据,纬度和经度维度保留全部
关闭数据集
%% [markdown]
## 特定一天
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决坐标轴负号显示问题
定义NetCDF文件路径 file_path = r"F:\HuaweiCup\DATA\data3\CHM_PRE_0.25dg_19612022.nc\CHM_PRE_0.25dg_19612022.nc"
打开NetCDF文件 dataset = nc.Dataset(file_path, mode='r')
获取数据 precipitation = dataset.variables['pre'][:] # 日降水数据
latitude = dataset.variables['latitude'][:] # 纬度
longitude = dataset.variables['longitude'][:] # 经度
time = dataset.variables['time'][:] # 时间维度
missing_value = -99.9 # 如果没有找到指定的标识符,使用默认值
将缺失值设为 NaN precipitation = np.where(precipitation == missing_value, np.nan, precipitation)
绘制第一个时间点的降水分布 plt.figure(figsize=(10, 6))
draw_deta = 1
使用第一个时间点的数据进行绘图 precipitation_at_time_0 = precipitation[draw_deta, :, :] # 选择时间维度为0的数据
绘制降水量的等高线图 plt.contourf(longitude, latitude, precipitation_at_time_0,
cmap='Blues', levels=20)
添加颜色条 plt.colorbar(label='降水量 (mm/day)')
设置图表标题和标签 plt.title(f"第{draw_deta}时间点的降水量分布", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
显示图像
关闭数据集
%% [markdown]
## 平均
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决坐标轴负号显示问题
定义NetCDF文件路径 file_path = r"F:\HuaweiCup\DATA\data3\CHM_PRE_0.25dg_19612022.nc\CHM_PRE_0.25dg_19612022.nc"
打开NetCDF文件 dataset = nc.Dataset(file_path, mode='r')
获取数据 precipitation = dataset.variables['pre'][:] # 日降水数据
latitude = dataset.variables['latitude'][:] # 纬度
longitude = dataset.variables['longitude'][:] # 经度
缺失值标识符
将缺失值设为 NaN precipitation = np.where(precipitation == missing_value, np.nan, precipitation)
对时间维度进行平均,保持空间维度不变 precipitation_mean = np.nanmean(precipitation, axis=0) # 对时间维度(axis=0)求平均
检查计算结果,确保没有负值 precipitation_mean = np.where(
precipitation_mean < 0, 0, precipitation_mean) # 将负值设为0
检查平均值的范围 print(
f"降水平均值最大值: {np.nanmax(precipitation_mean)}, 最小值: {np.nanmin(precipitation_mean)}")
绘制平均降水量分布 plt.figure(figsize=(10, 6))
plt.contourf(longitude, latitude, precipitation_mean,
cmap='Blues', levels=20, vmin=0, vmax=10) # 数据截断
plt.colorbar(label='平均降水量 (mm/day)')
plt.title("观测点时间维度上的平均降水量分布", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
显示图像
关闭数据集
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决坐标轴负号显示问题
定义NetCDF文件路径 file_path = r"F:\HuaweiCup\DATA\data3\CHM_PRE_0.25dg_19612022.nc\CHM_PRE_0.25dg_19612022.nc"
打开NetCDF文件 dataset = nc.Dataset(file_path, mode='r')
获取数据 precipitation = dataset.variables['pre'][:] # 日降水数据
latitude = dataset.variables['latitude'][:] # 纬度
longitude = dataset.variables['longitude'][:] # 经度
缺失值标识符
将缺失值设为 NaN precipitation = np.where(precipitation == missing_value, np.nan, precipitation)
对时间维度进行方差计算,保持空间维度不变 precipitation_variance = np.nanvar(precipitation, axis=0) # 对时间维度(axis=0)求方差
检查方差的范围 print(
f"降水方差最大值: {np.nanmax(precipitation_variance)}, 最小值: {np.nanmin(precipitation_variance)}")
绘制降水方差分布,截断方差图在500 plt.figure(figsize=(10, 6))
plt.contourf(longitude, latitude, precipitation_variance,
cmap='Blues', levels=20, vmin=0, vmax=500) # 数据截断
plt.colorbar(label='降水量方差 (mm^2/day)')
plt.title("观测点时间维度上的降水量方差分布", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
显示图像
关闭数据集
%% [markdown]
## 检查
%%
定义NetCDF文件路径 file_path = r"F:\HuaweiCup\DATA\data3\CHM_PRE_0.25dg_19612022.nc\CHM_PRE_0.25dg_19612022.nc"
打开NetCDF文件 dataset = nc.Dataset(file_path, mode='r')
获取数据 precipitation = dataset.variables['pre'][:] # 日降水数据
latitude = dataset.variables['latitude'][:] # 纬度
longitude = dataset.variables['longitude'][:] # 经度
缺失值标识符
将缺失值设为 NaN precipitation = np.where(precipitation == missing_value, np.nan, precipitation)
初始化全局最小值和最大值 global_min = np.nanmin(precipitation)
global_max = np.nanmax(precipitation)
合理的降水量范围 min_valid_precip = 0
max_valid_precip = 500
检查并打印异常值 invalid_mask = (precipitation < min_valid_precip) | (
precipitation > max_valid_precip)
if np.any(invalid_mask):
invalid_coords = np.argwhere(invalid_mask)
for coord in invalid_coords:
time_idx, lat_idx, lon_idx = coord
print(
f"异常值位置: 时间索引={time_idx}, 纬度索引={lat_idx}, 经度索引={lon_idx}, 值={precipitation[time_idx, lat_idx, lon_idx]}")
输出全局最大值和最小值 print(f"全局最小值: {global_min}")
print(f"全局最大值: {global_max}")
关闭数据集
%% [markdown]
## 土地利用
耕地(cropland)
森林(forest)
草地(grass)
灌木丛(shrub)
湿地(wetland)
%% import matplotlib.pyplot as plt
import os
import rasterio
import numpy as np
定义数据根目录 data_dir = r"F:\HuaweiCup\DATA\data4\data"
初始化总有效数据点数
遍历数据文件夹中的所有 TIFF 文件 for root, dirs, files in os.walk(data_dir):
for file in files:
if file.endswith(".tif"):
tif_file_path = os.path.join(root, file)
with rasterio.open(tif_file_path) as src:
# 获取文件的元数据信息
bounds = src.bounds # 获取边界(经纬度范围)
transform = src.transform # 获取仿射变换矩阵
crs = src.crs # 获取坐标参考系统
width, height = src.width, src.height # 获取图像的宽度和高度(像素)
count = src.count # 波段数量
dtype = src.dtypes[0] # 获取数据类型(例如 float32、int16 等)
code Copy code
# 获取经纬度分辨率
res = (transform[0], abs(transform[4]))
# 读取数据并统计有效值
data = src.read(1) # 读取第一波段数据
nodata = src.nodata # 获取缺失值标识符
# 将缺失值替换为 NaN
if nodata is not None:
data = np.where(data == nodata, np.nan, data)
# 计算该文件的有效数据点数
valid_pixels = np.count_nonzero(~np.isnan(data))
# 累积到总有效数据点数
total_valid_pixels += valid_pixels
# 输出每个文件的基本信息
print(f"处理文件: {file}")
print(f"图像宽度(像素数): {width}, 高度(像素数): {height}")
print(f"分辨率(经度, 纬度): {res}")
print(f"地理范围(左, 下, 右, 上): {bounds}")
print(f"有效数据点数: {valid_pixels}\n")
最终输出总有效数据点数 print(f"文件夹中所有TIFF文件的总有效数据点数: {total_valid_pixels}")
%% [markdown]
## 选择类型年份
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决坐标轴负号显示问题
定义数据根目录 data_dir = r"F:\HuaweiCup\DATA\data4\data"
可供选择的土地覆被类型和年份 cover_types = {
'耕地': 'cropland',
'森林': 'forest',
'草地': 'grass',
'灌木丛': 'shrub',
'湿地': 'wetland'
}
years = [str(year) for year in range(1900, 2020)]
def plot_land_cover(cover_type, year):
# 根据类型和年份生成文件路径
tif_file = os.path.join(data_dir, f"{cover_type}-{year}.tif")
code Copy code
if not os.path.exists(tif_file):
print(f"文件 {tif_file} 不存在,请检查输入是否正确")
return
# 打开并读取 TIFF 文件
with rasterio.open(tif_file) as src:
data = src.read(1) # 读取第一波段的数据
bounds = src.bounds # 获取图像的边界
# 确定图像的显示范围(extent)以匹配地理坐标
extent = [bounds.left, bounds.right, bounds.bottom, bounds.top]
# 绘制数据
plt.figure(figsize=(10, 8))
plt.imshow(data, cmap='viridis', extent=extent)
plt.colorbar(label="土地利用类型比例")
plt.title(f"{year}年{selected_type}分布", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
plt.xticks(range(int(bounds.left), int(bounds.right) + 1, 10)) # 离散化经度轴
plt.yticks(range(int(bounds.bottom), int(bounds.top) + 1, 5)) # 离散化纬度轴
plt.show()
用户输入选择 selected_type = '森林' # 选择 '耕地', '森林', '草地', '灌木丛', '湿地' 中之一
selected_year = '1956' # 选择可用年份,如 '1900', '1950', '2000'
调用绘图函数 plot_land_cover(cover_types[selected_type], selected_year)
%% [markdown]
cmap='Greys':灰度色
cmap='Blues':蓝色系
cmap='Reds':红色系
cmap='YlOrRd':从黄色到橙色再到红色
cmap='plasma':紫红色系
cmap='magma':深橙色系
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决坐标轴负号显示问题
定义数据根目录 data_dir = r"F:\HuaweiCup\DATA\data4\data"
可供选择的土地覆被类型和年份 cover_types = {
'耕地': 'cropland',
'森林': 'forest',
'草地': 'grass',
'灌木丛': 'shrub',
'湿地': 'wetland'
}
years = [str(year) for year in range(1900, 2020)]
def plot_land_cover(cover_type, year):
# 根据类型和年份生成文件路径
tif_file = os.path.join(data_dir, f"{cover_type}-{year}.tif")
code Copy code
if not os.path.exists(tif_file):
print(f"文件 {tif_file} 不存在,请检查输入是否正确")
return
# 打开并读取 TIFF 文件
with rasterio.open(tif_file) as src:
data = src.read(1) # 读取第一波段的数据
nodata = src.nodata # 获取缺失值标识符(如果存在)
bounds = src.bounds # 获取图像的边界
# 处理缺失值,将 nodata 值替换为 NaN
if nodata is not None:
data = np.where(data == nodata, np.nan, data)
# 确定图像的显示范围(extent)以匹配地理坐标
extent = [bounds.left, bounds.right, bounds.bottom, bounds.top]
# 设置颜色映射,并将 NaN 值设置为白色
cmap = plt.cm.Blues # 修改颜色映射
cmap.set_bad(color='white') # 将 NaN 设置为白色
# 绘制数据
plt.figure(figsize=(10, 8))
plt.imshow(data, cmap=cmap, extent=extent)
plt.colorbar(label="土地利用类型比例")
plt.title(f"{year}年{selected_type}分布", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
plt.xticks(range(int(bounds.left), int(bounds.right) + 1, 10)) # 离散化经度轴
plt.yticks(range(int(bounds.bottom), int(bounds.top) + 1, 5)) # 离散化纬度轴
plt.show()
用户输入选择 selected_type = '森林' # 选择 '耕地', '森林', '草地', '灌木丛', '湿地' 中之一
selected_year = '1956' # 选择可用年份,如 '1900', '1950', '2000'
调用绘图函数 plot_land_cover(cover_types[selected_type], selected_year)
%% [markdown]
## 五个 年平均
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决坐标轴负号显示问题
定义数据根目录 data_dir = r"F:\HuaweiCup\DATA\data4\data"
可供选择的土地覆被类型和年份 cover_types = {
'耕地': 'cropland',
'森林': 'forest',
'草地': 'grass',
'灌木丛': 'shrub',
'湿地': 'wetland'
}
定义每种土地覆盖类型的颜色映射 colormaps = {
'耕地': plt.cm.Reds, # 使用红色调
'森林': plt.cm.Greens, # 使用绿色调
'草地': plt.cm.Oranges, # 使用橙色调
'灌木丛': plt.cm.Purples, # 使用紫色调
'湿地': plt.cm.Blues # 使用蓝色调
}
def average_land_cover(cover_type, start_year, end_year, cmap):
total_data = None
count = 0
code Copy code
for year in range(start_year, end_year + 1):
tif_file = os.path.join(data_dir, f"{cover_type}-{year}.tif")
if not os.path.exists(tif_file):
print(f"文件 {tif_file} 不存在,跳过 {year}")
continue
# 打开并读取 TIFF 文件
with rasterio.open(tif_file) as src:
data = src.read(1) # 读取第一波段的数据
nodata = src.nodata # 获取缺失值标识符(如果存在)
bounds = src.bounds # 获取图像的边界
# 处理缺失值,将 nodata 值替换为 NaN
if nodata is not None:
data = np.where(data == nodata, np.nan, data)
# 初始化总数据数组
if total_data is None:
total_data = np.zeros_like(data, dtype=np.float32)
# 累加每年的数据
total_data = np.nansum([total_data, data], axis=0)
count += 1
# 计算平均值
average_data = total_data / count if count > 0 else None
# 绘制平均数据
if average_data is not None:
extent = [bounds.left, bounds.right, bounds.bottom, bounds.top]
cmap.set_bad(color='white') # 将 NaN 设置为白色
plt.figure(figsize=(10, 8))
plt.imshow(average_data, cmap=cmap, extent=extent)
plt.colorbar(label="土地利用类型比例")
plt.title(
f"{start_year}至{end_year}年{cover_types_count}的平均分布", fontsize=16)
plt.xlabel("经度", fontsize=12)
plt.ylabel("纬度", fontsize=12)
plt.xticks(range(int(bounds.left), int(
bounds.right) + 1, 10)) # 离散化经度轴
plt.yticks(range(int(bounds.bottom), int(
bounds.top) + 1, 5)) # 离散化纬度轴
plt.show()
用户输入选择 start_year = 1900 # 起始年份
end_year = 2019 # 结束年份
调用计算并绘图函数,为每种土地类型使用不同的颜色映射 for cover_types_count in cover_types:
average_land_cover(cover_types[cover_types_count],
start_year, end_year, colormaps[cover_types_count])
%%
设置中文字体支持 plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决坐标轴负号显示问题
定义数据根目录 data_dir = r"F:\HuaweiCup\DATA\data4\data"
定义土地覆被类型及其对应的英文名称 cover_types = {
'耕地': 'cropland',
'森林': 'forest',
'草地': 'grass',
'灌木丛': 'shrub',
'湿地': 'wetland'
}
定义每种土地覆盖类型的颜色 colors = {
'耕地': 'red',
'森林': 'green',
'草地': 'orange',
'灌木丛': 'purple',
'湿地': 'blue'
}
定义年份范围 start_year = 1990
end_year = 2019
years = list(range(start_year, end_year + 1))
初始化一个字典,用于存储每种类型每年的面积比例 proportion_data = {cover_type: [] for cover_type in cover_types.keys()}
假设每个像素代表的面积(例如,1平方公里) pixel_area = 1 # 根据实际情况修改
遍历每个年份 for year in years:
print(f"--------------------------------------------------")
print(f"正在处理年份: {year}")
yearly_areas = {}
for cn_type, en_type in cover_types.items():
tif_file = os.path.join(data_dir, f"{en_type}-{year}.tif")
code Copy code
if not os.path.exists(tif_file):
print(f"文件 {tif_file} 不存在,跳过 {year} 年的 {cn_type}")
yearly_areas[cn_type] = 0 # 缺失数据视为0
continue
try:
# 打开并读取 TIFF 文件
with rasterio.open(tif_file) as src:
data = src.read(1) # 读取第一波段的数据
nodata = src.nodata # 获取缺失值标识符(如果存在)
# 处理缺失值,将 nodata 值替换为 NaN
if nodata is not None:
data = np.where(data == nodata, np.nan, data)
# 确认数据的唯一值
unique_values = np.unique(data[~np.isnan(data)])
print(f"{cn_type} - {year}年数据唯一值: {unique_values}")
# 累加所有像素的覆盖比例
sum_pixels = np.nansum(data)
# 计算总面积
total_area = sum_pixels * pixel_area
yearly_areas[cn_type] = total_area
print(
f"{cn_type} - {year}年有效面积: {total_area:.4f} (覆盖比例总和: {sum_pixels:.4f})")
except Exception as e:
print(f"处理文件 {tif_file} 时出错: {e}")
yearly_areas[cn_type] = 0 # 出错数据视为0
# 计算总面积
total_yearly_area = sum(yearly_areas.values())
print(f"{year}年总面积: {total_yearly_area:.4f}")
if total_yearly_area == 0:
print(f"年份 {year} 的总面积为0,所有比例设置为0")
for cn_type in cover_types.keys():
proportion_data[cn_type].append(0)
else:
# 计算每种类型的比例并存储
for cn_type in cover_types.keys():
proportion = yearly_areas[cn_type] / total_yearly_area
proportion_data[cn_type].append(proportion)
print(f"{cn_type} - {year}年比例: {proportion:.4f}")
print("-" * 50) # 分隔线
检查是否有比例数据非零 for cn_type in cover_types.keys():
non_zero = [p for p in proportion_data[cn_type] if p > 0]
print(f"{cn_type} 有 {len(non_zero)} 个年份的比例大于0")
绘制折线图 plt.figure(figsize=(14, 8))
for cn_type in cover_types.keys():
plt.plot(years, proportion_data[cn_type],
label=cn_type, color=colors[cn_type])
plt.xlabel("年份", fontsize=14)
plt.ylabel("土地覆盖类型比例", fontsize=14)
plt.title("1990年至2019年五种土地覆盖类型变化趋势", fontsize=16)
plt.legend(fontsize=12)
plt.ylim(0, 1) # 设置纵轴范围为0到1
plt.grid(True)
plt.tight_layout()
plt.show()
python Copy code
# 导入必要的库
import os
import rasterio
from rasterio.warp import transform
import numpy as np
import pandas as pd
import netCDF4 as nc
from pyproj import Transformer
# ------------------------------
# 数据集1:高程、坡度、坡向(Albers 投影)
# ------------------------------
# 文件路径
dem_file = r"F:\HuaweiCup\DATA\data1\Albers_105\TIFF\chdem_105.tif"
aspect_file = r"F:\HuaweiCup\DATA\data1\Albers_105\TIFF\chdem_Aspect.tif"
slope_file = r"F:\HuaweiCup\DATA\data1\Albers_105\TIFF\chdem_Slope.tif"
# 打开高程数据
with rasterio.open(dem_file) as dem_src:
dem_data = dem_src.read(1)
dem_transform = dem_src.transform
dem_crs = dem_src.crs
dem_nodata = dem_src.nodata
with rasterio.open(aspect_file) as aspect_src:
aspect_data = aspect_src.read(1)
aspect_nodata = aspect_src.nodata
with rasterio.open(slope_file) as slope_src:
slope_data = slope_src.read(1)
slope_nodata = slope_src.nodata
# 将 nodata 值替换为 np.nan
dem_data = np.where(dem_data == dem_nodata, np.nan, dem_data)
aspect_data = np.where(aspect_data == aspect_nodata, np.nan, aspect_data)
slope_data = np.where(slope_data == slope_nodata, np.nan, slope_data)
# 确保数据形状一致
assert dem_data.shape == aspect_data.shape == slope_data.shape
# 创建像素坐标网格
n_rows, n_cols = dem_data.shape
rows, cols = np.indices((n_rows, n_cols))
# 将像素坐标转换为投影坐标
xs, ys = rasterio.transform.xy(dem_transform, rows, cols)
xs = np.array(xs)
ys = np.array(ys)
# 将投影坐标转换为地理坐标(WGS84,经纬度)
transformer = Transformer.from_crs(dem_crs, 'EPSG:4326', always_xy=True)
longitudes, latitudes = transformer.transform(xs, ys)
# 将数组展开为一维
latitudes = latitudes.flatten()
longitudes = longitudes.flatten()
elevations = dem_data.flatten()
aspects = aspect_data.flatten()
slopes = slope_data.flatten()
# 移除缺失值
mask = (~np.isnan(elevations)) & (~np.isnan(aspects)) & (~np.isnan(slopes))
latitudes = latitudes[mask]
longitudes = longitudes[mask]
elevations = elevations[mask]
aspects = aspects[mask]
slopes = slopes[mask]
# 创建 DataFrame
elevation_df = pd.DataFrame({
'latitude': latitudes,
'longitude': longitudes,
'elevation': elevations,
'aspect': aspects,
'slope': slopes
})
# 采样到 0.01 度的网格
elevation_df['latitude'] = elevation_df['latitude'].round(2)
elevation_df['longitude'] = elevation_df['longitude'].round(2)
elevation_df = elevation_df.drop_duplicates(subset=['latitude', 'longitude'])
# ------------------------------
# 数据集2:气温(1979-2018 年每日数据)
# ------------------------------
temp_data_list = []
temp_data_dir = r"F:\HuaweiCup\DATA\data2\day_avg"
for year in range(1979, 2019):
year_str = str(year)
year_dir = os.path.join(temp_data_dir, f"{year_str}_avg")
if not os.path.exists(year_dir):
continue
tiff_files = [f for f in os.listdir(year_dir) if f.endswith('_avg.tif')]
max_temp = None
for tiff_file in tiff_files:
tiff_path = os.path.join(year_dir, tiff_file)
with rasterio.open(tiff_path) as src:
data = src.read(1).astype(np.float32)
nodata = src.nodata
data = np.where(data == nodata, np.nan, data)
if max_temp is None:
max_temp = data
else:
max_temp = np.nanmax(np.dstack((max_temp, data)), axis=2)
if max_temp is None:
continue
n_rows, n_cols = max_temp.shape
rows, cols = np.indices((n_rows, n_cols))
xs, ys = rasterio.transform.xy(src.transform, rows, cols)
xs = np.array(xs)
ys = np.array(ys)
longitudes = xs.flatten()
latitudes = ys.flatten()
temperatures = max_temp.flatten()
mask = ~np.isnan(temperatures)
latitudes = latitudes[mask]
longitudes = longitudes[mask]
temperatures = temperatures[mask]
temp_df = pd.DataFrame({
'year': year,
'latitude': latitudes,
'longitude': longitudes,
'temperature': temperatures
})
temp_df['latitude'] = temp_df['latitude'].round(2)
temp_df['longitude'] = temp_df['longitude'].round(2)
temp_df = temp_df.drop_duplicates(subset=['latitude', 'longitude', 'year'])
temp_data_list.append(temp_df)
temp_data = pd.concat(temp_data_list, ignore_index=True)
# ------------------------------
# 数据集3:降水(1961-2022 年每日数据)
# ------------------------------
nc_file = r"F:\HuaweiCup\DATA\data3\CHM_PRE_0.25dg_19612022.nc\CHM_PRE_0.25dg_19612022.nc"
dataset = nc.Dataset(nc_file)
precipitation = dataset.variables['pre'][:]
latitude = dataset.variables['latitude'][:]
longitude = dataset.variables['longitude'][:]
time = dataset.variables['time'][:]
time_units = dataset.variables['time'].units
dates = nc.num2date(time, units=time_units)
years = np.array([date.year for date in dates])
unique_years = np.unique(years)
lon_grid, lat_grid = np.meshgrid(longitude, latitude)
latitudes = lat_grid.flatten()
longitudes = lon_grid.flatten()
precipitation_data_list = []
for year in unique_years:
if year < 1990 or year > 2015:
continue
indices = np.where(years == year)[0]
pre_year = precipitation[indices, :, :]
max_precip = np.nanmax(pre_year, axis=0)
precip_flat = max_precip.flatten()
mask = ~np.isnan(precip_flat)
latitudes_masked = latitudes[mask]
longitudes_masked = longitudes[mask]
precip_flat_masked = precip_flat[mask]
precip_df = pd.DataFrame({
'year': year,
'latitude': latitudes_masked,
'longitude': longitudes_masked,
'precipitation': precip_flat_masked
})
precip_df['latitude'] = precip_df['latitude'].round(2)
precip_df['longitude'] = precip_df['longitude'].round(2)
precip_df = precip_df.drop_duplicates(subset=['latitude', 'longitude', 'year'])
precipitation_data_list.append(precip_df)
precipitation_data = pd.concat(precipitation_data_list, ignore_index=True)
dataset.close()
# ------------------------------
# 数据集4:土地利用(1900-2019 年,每年数据)
# ------------------------------
land_use_dir = r"F:\HuaweiCup\DATA\data4\data"
land_cover_types = ['cropland', 'forest', 'grass', 'shrub', 'wetland']
years = range(1990, 2016)
land_use_data_list = []
for year in years:
land_cover_data = {}
for land_cover in land_cover_types:
land_cover_file = os.path.join(land_use_dir, f"{land_cover}-{year}.tif")
if not os.path.exists(land_cover_file):
continue
with rasterio.open(land_cover_file) as src:
data = src.read(1).astype(np.float32)
nodata = src.nodata
data = np.where(data == nodata, np.nan, data)
land_cover_data[land_cover] = data
if not land_cover_data:
continue
n_rows, n_cols = list(land_cover_data.values())[0].shape
rows, cols = np.indices((n_rows, n_cols))
xs, ys = rasterio.transform.xy(src.transform, rows, cols)
xs = np.array(xs)
ys = np.array(ys)
longitudes = xs.flatten()
latitudes = ys.flatten()
max_proportions = np.full((n_rows * n_cols,), np.nan)
max_land_cover = np.full((n_rows * n_cols,), '', dtype=object)
for idx in range(len(max_proportions)):
proportions = []
for land_cover in land_cover_types:
if land_cover in land_cover_data:
proportion = land_cover_data[land_cover].flatten()[idx]
proportions.append(proportion)
else:
proportions.append(np.nan)
proportions = np.array(proportions)
if np.all(np.isnan(proportions)):
continue
max_idx = np.nanargmax(proportions)
max_proportions[idx] = proportions[max_idx]
max_land_cover[idx] = land_cover_types[max_idx]
mask = ~np.isnan(max_proportions)
latitudes_masked = latitudes[mask]
longitudes_masked = longitudes[mask]
max_land_cover_masked = max_land_cover[mask]
land_use_df = pd.DataFrame({
'year': year,
'latitude': latitudes_masked,
'longitude': longitudes_masked,
'land_use': max_land_cover_masked
})
land_use_df['latitude'] = land_use_df['latitude'].round(2)
land_use_df['longitude'] = land_use_df['longitude'].round(2)
land_use_df = land_use_df.drop_duplicates(subset=['latitude', 'longitude', 'year'])
land_use_data_list.append(land_use_df)
land_use_data = pd.concat(land_use_data_list, ignore_index=True)
# ------------------------------
# 数据集5:人口(1990-2015 年,每年数据)
# ------------------------------
pop_data_dir = r"F:\HuaweiCup\DATA\data5\pop_output"
pop_data_list = []
for year in range(1990, 2016):
pop_file = os.path.join(pop_data_dir, f"pop{year}", f"pop{year}.tif")
if not os.path.exists(pop_file):
continue
with rasterio.open(pop_file) as src:
data = src.read(1).astype(np.float32)
nodata = src.nodata
data = np.where(data == nodata, np.nan, data)
n_rows, n_cols = data.shape
rows, cols = np.indices((n_rows, n_cols))
xs, ys = rasterio.transform.xy(src.transform, rows, cols)
xs = np.array(xs)
ys = np.array(ys)
longitudes = xs.flatten()
latitudes = ys.flatten()
population = data.flatten()
mask = ~np.isnan(population)
latitudes = latitudes[mask]
longitudes = longitudes[mask]
population = population[mask]
pop_df = pd.DataFrame({
'year': year,
'latitude': latitudes,
'longitude': longitudes,
'population': population
})
pop_df['latitude'] = pop_df['latitude'].round(2)
pop_df['longitude'] = pop_df['longitude'].round(2)
pop_df = pop_df.drop_duplicates(subset=['latitude', 'longitude', 'year'])
pop_data_list.append(pop_df)
pop_data = pd.concat(pop_data_list, ignore_index=True)
# ------------------------------
# 数据集6:GDP(1990-2015 年,每年数据)
# ------------------------------
gdp_data_dir = r"F:\HuaweiCup\DATA\data6\GDP_output"
gdp_data_list = []
for year in range(1990, 2016):
gdp_file = os.path.join(gdp_data_dir, f"gdp{year}.tif")
if not os.path.exists(gdp_file):
continue
with rasterio.open(gdp_file) as src:
data = src.read(1).astype(np.float32)
nodata = src.nodata
data = np.where(data == nodata, np.nan, data)
n_rows, n_cols = data.shape
rows, cols = np.indices((n_rows, n_cols))
xs, ys = rasterio.transform.xy(src.transform, rows, cols)
xs = np.array(xs)
ys = np.array(ys)
longitudes = xs.flatten()
latitudes = ys.flatten()
gdp = data.flatten()
mask = ~np.isnan(gdp)
latitudes = latitudes[mask]
longitudes = longitudes[mask]
gdp = gdp[mask]
gdp_df = pd.DataFrame({
'year': year,
'latitude': latitudes,
'longitude': longitudes,
'gdp': gdp
})
gdp_df['latitude'] = gdp_df['latitude'].round(2)
gdp_df['longitude'] = gdp_df['longitude'].round(2)
gdp_df = gdp_df.drop_duplicates(subset=['latitude', 'longitude', 'year'])
gdp_data_list.append(gdp_df)
gdp_data = pd.concat(gdp_data_list, ignore_index=True)
# ------------------------------
# 合并所有数据
# ------------------------------
# 按照 'year', 'latitude', 'longitude' 进行合并
data_frames = [temp_data, precipitation_data, land_use_data, pop_data, gdp_data]
# 依次合并数据集
from functools import reduce
combined_data = reduce(lambda left, right: pd.merge(left, right, on=['year', 'latitude', 'longitude'], how='inner'), data_frames)
# 合并高程数据(无年份)
combined_data = pd.merge(combined_data, elevation_df, on=['latitude', 'longitude'], how='inner')
# 保存到 CSV 文件
combined_data.to_csv('combined_data.csv', index=False, encoding='utf-8')
# 输出完成信息
print("数据处理完成,结果已保存到 combined_data.csv")
以上代码实现了对六个数据集的读取、预处理,并将它们合并到一个 DataFrame 中,最后导出为 UTF-8 编码的 CSV 文件 combined_data.csv。请根据您的实际数据路径和需求调整代码。
Show full message · 382 lines Copy first response
Not yet included in a published release.