python - 在 Python 中读取 .grd 文件

标签 python numpy pandas gis raster

一些ESRI网格格式的文件(后缀为.grd)是一个具有左下X角、左下Y角和值的地理空间数据集。

文件看起来像这样(使用 vim 读取它):

   1 ncols 2880
   2 nrows 1440
   3 xllcorner -180.0
   4 yllcorner  -90.0
   5 cellsize 0.125
   6 nodata_value -999
   7 version 2.0

   8  -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 ...

目前,我使用手动预处理方法处理这些文件。

  1. 删除前 7 行
  2. 将 .grd 文件保存到 .txt 文件中。
  3. 使用 numpy 将 .txt 文件读取到表示空间属性的 numpy 数组中
  4. 结合前7行,生成属性数组对应的Lon和Lat数组(For my cas (1440 x 2880))

现在,我想实现直接读取文件:

  • 值 -> 从第 8 行开始
  • 经度 -> 由 ncols、cellsize 和 xllcorner 生成
  • 经度 -> 由 nrows、cellsize 和 yllcorner 生成器

我的尝试

 ## Read the first seven lines using LineCache
 ncols = linecache.getline("grd file", 1)
 ......
 ## Read the array using np.loadtxt()
 myArray  = np.loadtxt("grd file", skiprows=7) 

最佳答案

你可以为它写一个函数。这是一个示例(假设您的行号来自 vim,实际上并不存在于文件中):

import numpy as np

def read_grd(filename):
    with open(filename) as infile:
        ncols = int(infile.readline().split()[1])
        nrows = int(infile.readline().split()[1])
        xllcorner = float(infile.readline().split()[1])
        yllcorner = float(infile.readline().split()[1])
        cellsize = float(infile.readline().split()[1])
        nodata_value = int(infile.readline().split()[1])
        version = float(infile.readline().split()[1])
    longitude = xllcorner + cellsize * np.arange(ncols)
    latitude = xllcorner + cellsize * np.arange(nrows)
    value = np.loadtxt(filename, skiprows=7)

    return longitude, latitude, value

关于python - 在 Python 中读取 .grd 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37855316/

相关文章:

python - 要列出的字节字符串

python - 将 Pandas 数据框转换为带有标题和数据类型的 numpy 数组

python - pandas 和 numpy 的意思不同

python - 如何使用 iloc[] 选择 pandas 数据框的倒数第二行?

python - Tensorflow:将现有图多次复制到新图中

python - 用灰色背景填充图像数组

python - 为什么 pyplot.contour() 要求 Z 是二维数组?

python - 使用muliprocessing或hadoop加速大数据上的python-pandas脚本

python - 更改 pandas 数据帧多重索引中的值

python - TypeError : tuple indices must be integers