请编写代码,完成对六个数据集的读取、预处理、整理到dataframe(六… · 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 # 计算总的数据点数(像素数)
# 如果有缺失值标识符,替换为 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()
Assistant2024-09-23 19:58 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 01m7h41vbjsmn0y15m94na8fb5Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 2e7359caa51ae907736a14ac52c9113d
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
%% [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
# 打开并读取 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)
# 获取该年份下所有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 # 计算总的数据点数(像素数)
# 如果有缺失值标识符,替换为 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 # 获取缺失值标识符
# 如果有缺失值标识符,替换为 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')]
# 遍历每个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 等)
# 获取经纬度分辨率
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")
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")
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
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")
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()
下面是实现您所要求的完整代码。该代码将六个数据集读取、预处理,并整理到一个 DataFrame 中,最后导出为 UTF-8 的 CSV 文件。按照您的要求,代码包括以下功能:
按年为粒度,包含经纬度信息,进行 0.01 的网格采样 。
气温、降水分别取每年的日最大值 。
土地利用选择采样点占比最大的类型 。
高程(海拔)使用第二种 Albers 投影的数据,包括海拔、坡度、坡向三列 。
请确保在运行代码前安装必要的 Python 库,例如 rasterio、netCDF4、numpy、pandas 等。
import os
import numpy as np
import pandas as pd
import rasterio
from rasterio.warp import transform
from rasterio.crs import CRS
from rasterio.sample import sample_gen
from netCDF4 import Dataset, num2date
from tqdm import tqdm # 用于显示进度条
# 定义研究区域的经纬度范围和网格分辨率
min_lon, max_lon = 73.0, 135.0
min_lat, max_lat = 18.0, 54.0
grid_res = 0.01 # 0.01 度的网格采样
# 生成经纬度网格点
lons = np.arange(min_lon, max_lon, grid_res)
lats = np.arange(min_lat, max_lat, grid_res)
lon_grid, lat_grid = np.meshgrid(lons, lats)
points = np.vstack((lon_grid.ravel(), lat_grid.ravel())).T
# 将点转换为列表形式,方便后续处理
points_list = list(zip(points[:, 0], points[:, 1]))
# 用于存储最终数据的列表
data_list = []
# -----------------------------------
# 1. 读取高程数据(海拔、坡度、坡向)
# -----------------------------------
# 高程数据文件路径
dem_file = r"F:\HuaweiCup\DATA\data1\Albers_105\TIFF\chdem_105.tif"
slope_file = r"F:\HuaweiCup\DATA\data1\Albers_105\TIFF\chdem_Slope.tif"
aspect_file = r"F:\HuaweiCup\DATA\data1\Albers_105\TIFF\chdem_Aspect.tif"
# 打开高程数据集
with rasterio.open(dem_file) as dem_dataset, \
rasterio.open(slope_file) as slope_dataset, \
rasterio.open(aspect_file) as aspect_dataset:
# 获取投影信息
dem_crs = dem_dataset.crs
# 将 WGS84 坐标转换为 Albers 投影坐标
xs, ys = transform(CRS.from_epsg(4326), dem_crs, points[:, 0], points[:, 1])
albers_points = list(zip(xs, ys))
# 采样海拔、坡度、坡向值
dem_values = [val[0] for val in dem_dataset.sample(albers_points)]
slope_values = [val[0] for val in slope_dataset.sample(albers_points)]
aspect_values = [val[0] for val in aspect_dataset.sample(albers_points)]
# 将结果转换为数组
dem_values = np.array(dem_values)
slope_values = np.array(slope_values)
aspect_values = np.array(aspect_values)
# -----------------------------------
# 2. 读取气温数据(每年的日最大值)
# -----------------------------------
# 气温数据根目录
temperature_data_dir = r"F:\HuaweiCup\DATA\data2\day_avg"
# 定义处理的年份范围
years = range(1990, 2016) # 1990-2015
# 创建一个字典来存储每年对应的最大气温值
temperature_max_dict = {}
for year in tqdm(years, desc="处理气温数据"):
year = str(year)
year_dir = os.path.join(temperature_data_dir, f"{year}_avg")
if not os.path.exists(year_dir):
print(f"气温数据年份目录 {year_dir} 不存在,跳过该年。")
continue
# 获取该年份下的所有 TIFF 文件
tiff_files = [f for f in os.listdir(year_dir) if f.endswith('_avg.tif')]
tiff_files.sort()
annual_max_temp = None
for tiff_file in tiff_files:
file_path = os.path.join(year_dir, tiff_file)
with rasterio.open(file_path) as src:
# 将温度数据读取并采样
temp_data = src.read(1)
temp_data = np.where(temp_data == src.nodata, np.nan, temp_data)
temp_values = np.array([val[0] for val in src.sample(points_list)])
# 更新年最大值
if annual_max_temp is None:
annual_max_temp = temp_values
else:
annual_max_temp = np.fmax(annual_max_temp, temp_values)
temperature_max_dict[year] = annual_max_temp
# -----------------------------------
# 3. 读取降水数据(每年的日最大值)
# -----------------------------------
# 降水数据文件路径
precipitation_file = r"F:\HuaweiCup\DATA\data3\CHM_PRE_0.25dg_19612022.nc\CHM_PRE_0.25dg_19612022.nc"
# 打开 NetCDF 数据集
with Dataset(precipitation_file, mode='r') as dataset:
# 获取变量
pre_data = dataset.variables['pre'] # (time, lat, lon)
time_var = dataset.variables['time']
times = num2date(time_var[:], units=time_var.units)
latitude = dataset.variables['latitude'][:]
longitude = dataset.variables['longitude'][:]
# 创建经纬度到索引的映射
lat_to_idx = {lat: idx for idx, lat in enumerate(latitude)}
lon_to_idx = {lon: idx for idx, lon in enumerate(longitude)}
# 将经纬度坐标与 NetCDF 数据集的索引对应
def get_nearest_idx(value, array):
idx = (np.abs(array - value)).argmin()
return idx
# 构建一个字典来存储每年对应的最大降水量
precipitation_max_dict = {}
for year in tqdm(years, desc="处理降水数据"):
# 找到对应年份的时间索引
year_indices = [i for i, dt in enumerate(times) if dt.year == year]
if not year_indices:
print(f"降水数据中没有年份 {year} 的数据,跳过该年。")
continue
annual_max_pre = None
for idx in year_indices:
# 获取该时间步的降水数据
pre_slice = pre_data[idx, :, :]
pre_slice = np.where(pre_slice == -99.9, np.nan, pre_slice)
# 对采样点进行插值或取最近值
pre_values = []
for lon, lat in points_list:
lat_idx = get_nearest_idx(lat, latitude)
lon_idx = get_nearest_idx(lon, longitude)
pre_values.append(pre_slice[lat_idx, lon_idx])
pre_values = np.array(pre_values)
# 更新年最大值
if annual_max_pre is None:
annual_max_pre = pre_values
else:
annual_max_pre = np.fmax(annual_max_pre, pre_values)
precipitation_max_dict[str(year)] = annual_max_pre
# -----------------------------------
# 4. 读取土地利用数据(选择占比最大的类型)
# -----------------------------------
# 土地利用数据根目录
landuse_data_dir = r"F:\HuaweiCup\DATA\data4\data"
# 土地利用类型及对应的文件名
landuse_types = {
'cropland': '耕地',
'forest': '森林',
'grass': '草地',
'shrub': '灌木丛',
'wetland': '湿地'
}
# 构建一个字典来存储每年的主导土地利用类型
landuse_major_dict = {}
for year in tqdm(years, desc="处理土地利用数据"):
year = str(year)
# 初始化一个数组来存储每个类型的占比
landuse_proportions = np.zeros((len(points_list), len(landuse_types)))
for idx, (type_en, type_cn) in enumerate(landuse_types.items()):
file_path = os.path.join(landuse_data_dir, f"{type_en}-{year}.tif")
if not os.path.exists(file_path):
print(f"土地利用数据文件 {file_path} 不存在,使用 NaN 填充。")
landuse_values = np.full(len(points_list), np.nan)
else:
with rasterio.open(file_path) as src:
landuse_data = src.read(1)
landuse_data = np.where(landuse_data == src.nodata, np.nan, landuse_data)
landuse_values = np.array([val[0] for val in src.sample(points_list)])
landuse_proportions[:, idx] = landuse_values
# 找到每个点占比最大的类型的索引
major_indices = np.nanargmax(landuse_proportions, axis=1)
# 获取对应的土地利用类型
major_types = [list(landuse_types.values())[idx] for idx in major_indices]
landuse_major_dict[year] = major_types
# -----------------------------------
# 5. 读取人口和 GDP 数据
# -----------------------------------
# 人口和 GDP 数据根目录
population_data_dir = r"F:\HuaweiCup\DATA\data5\pop_output"
gdp_data_dir = r"F:\HuaweiCup\DATA\data6\GDP_output"
population_dict = {}
gdp_dict = {}
for year in tqdm(years, desc="处理人口和 GDP 数据"):
year = str(year)
# 人口数据
pop_file = os.path.join(population_data_dir, f"pop{year}", f"pop{year}.tif")
if not os.path.exists(pop_file):
print(f"人口数据文件 {pop_file} 不存在,使用 NaN 填充。")
pop_values = np.full(len(points_list), np.nan)
else:
with rasterio.open(pop_file) as src:
pop_data = src.read(1)
pop_data = np.where(pop_data == src.nodata, np.nan, pop_data)
pop_values = np.array([val[0] for val in src.sample(points_list)])
population_dict[year] = pop_values
# GDP 数据
gdp_file = os.path.join(gdp_data_dir, f"gdp{year}.tif")
if not os.path.exists(gdp_file):
print(f"GDP 数据文件 {gdp_file} 不存在,使用 NaN 填充。")
gdp_values = np.full(len(points_list), np.nan)
else:
with rasterio.open(gdp_file) as src:
gdp_data = src.read(1)
gdp_data = np.where(gdp_data == src.nodata, np.nan, gdp_data)
gdp_values = np.array([val[0] for val in src.sample(points_list)])
gdp_dict[year] = gdp_values
# -----------------------------------
# 6. 整合所有数据到 DataFrame
# -----------------------------------
# 遍历每个年份,构建 DataFrame
for idx, (lon, lat) in enumerate(tqdm(points_list, desc="整合数据")):
for year in years:
year = str(year)
data = {
'longitude': lon,
'latitude': lat,
'year': int(year),
'elevation': dem_values[idx],
'slope': slope_values[idx],
'aspect': aspect_values[idx],
'max_temperature': temperature_max_dict.get(year, [np.nan]*len(points_list))[idx],
'max_precipitation': precipitation_max_dict.get(year, [np.nan]*len(points_list))[idx],
'land_use': landuse_major_dict.get(year, [np.nan]*len(points_list))[idx],
'population': population_dict.get(year, [np.nan]*len(points_list))[idx],
'GDP': gdp_dict.get(year, [np.nan]*len(points_list))[idx]
}
data_list.append(data)
# 创建 DataFrame
df = pd.DataFrame(data_list)
# -----------------------------------
# 7. 导出为 UTF-8 的 CSV 文件
# -----------------------------------
output_file = 'combined_data.csv'
df.to_csv(output_file, index=False, encoding='utf-8')
print(f"数据已成功导出到 {output_file}")
注意事项:
计算资源 :由于数据量较大,处理过程中可能需要大量的内存和计算时间。建议在运行代码前确保有足够的计算资源,或者适当降低采样分辨率(例如,将 grid_res 设置为 0.05 或更大)。
进度条 :tqdm 库用于显示处理进度。如果没有安装该库,可以使用 pip install tqdm 进行安装,或者删除 tqdm 相关的代码。
数据路径 :请确保在代码中正确设置了各个数据集的文件路径。
缺失值处理 :代码中对于缺失数据进行了处理,使用 NaN 进行填充。
投影转换 :在处理空间数据时,代码对不同数据的投影进行了转换和匹配,确保采样点在不同数据集之间对齐。
总结:
上述代码实现了对六个数据集的读取、预处理,并将其整合到一个包含经纬度、年份、以及各项指标的 DataFrame 中,最终导出为 UTF-8 编码的 CSV 文件。这样,您就可以在后续的分析中直接使用该数据进行研究。
如果您有任何疑问或需要进一步的帮助,请随时告诉我!
Copy first response
Not yet included in a published release.