【问题标题】:printing function output to csv in python在python中将函数输出打印到csv
【发布时间】:2018-06-28 06:51:40
【问题描述】:

我是 Python 的初学者,我需要以 csv/xlsx 格式导出我的函数输出。 请看我的代码。 我需要将 pixel2coord 函数的输出打印到 csv。谢谢

from osgeo import gdal
# Open raster file
ds = gdal.Open('C:\\Users\\ADMIN\\Desktop\\datanew\\ndvi_alig_landsat_clipped.img')
# GDAL affine transform parameters, According to gdal documentation xoff/yoff are image left corner, a/e are pixel wight/height and b/d is rotation and is zero if image is north up. 
xoff, a, b, yoff, d, e = ds.GetGeoTransform() 
def pixel2coord(x, y):
    """Returns global coordinates from pixel x, y coords"""   
    xp = a * x + b * y + xoff
    yp = d * x + e * y + yoff
    return(xp, yp)
# get columns and rows of your image from gdalinfo
rows = 15381+1
colms = 15081+1

if __name__ == "__main__":
    for row in  range(0,rows):
        for col in  range(0,colms): 
            print pixel2coord(col,row)

【问题讨论】:

  • 请将代码复制并粘贴为您的问题的文本
  • 好的。做到了@roganjosh
  • 我复制了代码并将其粘贴为文本@GMB。谢谢
  • 这与将大矩阵写入 csv 的一般情况有什么不同吗?如果没有,您可能会发现 csv 模块很有用。
  • 我的建议是将其打印为“逗号分隔值”:打开一个“常规”文本文件,而不是将数字作为字符串写入:file.write("{},{}\n".format(x,y))

标签: python geocoding latitude-longitude


【解决方案1】:

这是您感兴趣的代码:

if __name__ == "__main__":
    file=open("file.csv","w") ## open file in write mode
    for row in  range(0,rows):
        for col in  range(0,colms): 
            x,y = pixel2coord(col,row)
            print "({},{})".format(x,y)
            lat= ## x or y
            long= ## x or y
            file.write("{};{}\n".format(lat,long)) ## write each coordinate comma-separated

PS:我使用的是欧式 csv(分号分隔),如果您是美国人,请随意用逗号替换分号(在字符串内)

【讨论】:

  • 感谢您的回复。这将输出作为 file.csv 工作表中的单独行和列值。我需要 col 是经度和 row 是纬度的坐标。
  • 我编辑了上面的脚本:您只需选择“什么”是从您的函数返回的纬度和经度(以 x 和 y 表示)值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多