You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python从含UTM网格的DataFrame生成TIFF图像

用Python将UTM网格DataFrame生成TIFF图像

所需依赖

先安装必要的Python库:

pip install pandas rasterio numpy

实现步骤与代码

假设你已经有了包含E(UTM东向坐标)、N(UTM北向坐标)和value列的DataFrame,以下是生成TIFF的完整流程:

  1. 整理网格坐标与值
    提取并排序唯一的UTM坐标,确定栅格范围和分辨率,再将value值映射为二维数组:

    import pandas as pd
    import numpy as np
    import rasterio
    from rasterio.transform import from_origin
    
    # 假设你的DataFrame名为df
    # 提取并排序唯一的E、N坐标(北向坐标倒序,匹配TIFF从上到下的存储逻辑)
    e_coords = sorted(df['E'].unique())
    n_coords = sorted(df['N'].unique(), reverse=True)
    
    # 计算规则网格的分辨率
    res_e = e_coords[1] - e_coords[0]
    res_n = n_coords[0] - n_coords[1]
    
    # 初始化栅格数组
    raster_array = np.zeros((len(n_coords), len(e_coords)), dtype=np.float32)
    
    # 填充数组:匹配每个坐标对应的value值
    for _, row in df.iterrows():
        e_idx = e_coords.index(row['E'])
        n_idx = n_coords.index(row['N'])
        raster_array[n_idx, e_idx] = row['value']
    
  2. 设置TIFF地理信息
    定义地理变换参数(左上角坐标、分辨率),并指定对应的UTM坐标系(替换为你的UTM带对应的EPSG代码,例如UTM 30N对应EPSG:32630):

    # 栅格左上角坐标:最小E值、最大N值
    left = min(e_coords)
    top = max(n_coords)
    
    # 创建地理变换对象
    transform = from_origin(left, top, res_e, res_n)
    
    # 设置坐标系(替换为你的UTM对应的EPSG代码)
    crs = rasterio.crs.CRS.from_epsg(326XX)
    
  3. 写入TIFF文件
    用rasterio将栅格数组写入TIFF:

    with rasterio.open(
        'output_grid.tif',
        'w',
        driver='GTiff',
        height=raster_array.shape[0],
        width=raster_array.shape[1],
        count=1,
        dtype=raster_array.dtype,
        crs=crs,
        transform=transform,
    ) as dst:
        dst.write(raster_array, 1)
    

注意事项

  • 确保你的DataFrame是规则网格(每个E、N组合唯一且无缺失),若存在缺失值,可将数组初始值设为np.nan,并在写入时通过nodata=np.nan指定无数据值。
  • EPSG代码必须与你的UTM带严格匹配,否则TIFF的地理定位会出错。

内容的提问来源于stack exchange,提问作者Vitor Bento

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 15:33:12