简体   繁体   English

在Python中获取2D数组的索引

[英]Get Index of 2D array in Python

I use osgeo from gdal module for processing geographic raster data. 我使用来自gdal模块的osgeo处理地理栅格数据。

#Get size of input raster (cols, rows)
cols = ds.RasterXSize #3531
rows = ds.RasterYSize #3314

So to read all the data, I create an array: 因此,要读取所有数据,我创建一个数组:

data = band.ReadAsArray(0, 0, cols, rows).astype(float)

Result of ReadAsArray is a 2D numpy array. ReadAsArray的结果是2D numpy数组。 Until here it works. 直到这里工作。

So in order to further apply the geographic transformation for each pixel in that raster, I need the column index and the row index for each pixel. 因此,为了进一步对该栅格中的每个像素应用地理变换,我需要每个像素的列索引和行索引。 I think I might need a numpy function to read that out, but I have no clue how that works with a 2D array. 我想我可能需要一个numpy函数来读取该信息,但是我不知道它如何与2D数组一起工作。

I can access items the array by simply calling its index (eg band[0][1]), but I'd need the whole column index and the whole row index separately stored in eg col_idx and row_idx. 我可以通过简单地调用数组的索引(例如band [0] [1])来访问数组的项目,但是我需要整个列索引和整个行索引分别存储在例如col_idx和row_idx中。

I tried with something like that, but didn't work: 我尝试了类似的方法,但是没有用:

for idx, val in enumerate(ints):
    print idx, val

Any help appreciated! 任何帮助表示赞赏!

you can use numpy.meshgrid 您可以使用numpy.meshgrid

i, j = numpy.meshgrid(range(ncols), range(nrows))
result = f(data, i, j)

Example

In [28]: nrows = 2 ; ncols = 4

In [29]: icol, irow = np.meshgrid(range(ncols),range(nrows))

In [30]: def a(r,c): return 100*r+c

In [31]: a(irow, icol)
Out[31]: 
array([[  0,   1,   2,   3],
       [100, 101, 102, 103]])

In [32]: 

data is XXXL? 数据是XXXL?

In this case, instead of generating two large matrices with the row and column indices, you can use a for loop on the rows of your array (it's slower but not as slow as a double for loop) 在这种情况下,您可以在数组的行上使用for循环,而不是使用行和列索引生成两个大型矩阵( 速度较慢,但不如double for循环慢)

icol = range(ncols)
for irow, row in enumerate(data):
    if irow>0:
         result = np.vstack((result, f(row, irow, icol)))
    else:
         result = f(row, irow, icol)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM