<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Raster to XYZ CSV in Python Questions</title>
    <link>https://community.esri.com/t5/python-questions/raster-to-xyz-csv/m-p/1116113#M62962</link>
    <description>&lt;P&gt;Not sure what parts of the script is doing, so just an example for consideration.&lt;/P&gt;&lt;P&gt;Starting with a 2d numpy array and convert it to 2 forms of xyz arrays.&amp;nbsp; The last, a structured array with field names, makes it easier to convert to a csv.&lt;/P&gt;&lt;LI-CODE lang="python"&gt;    a = np.random.randint(0, 10, size=(4, 3))
    a_st = []
    idx = np.indices(a.shape)
    x = idx[0].flatten()
    y = idx[1].flatten()
    vals = a.flatten()
    xy = list(zip(x, y, vals))
    dt = [('X', '&amp;lt;f8'), ('Y', '&amp;lt;f8'), ('Val', '&amp;lt;i4')]
    xy = np.asarray(xy, dtype=dt)
    print("syntax... a\n{!r:}\nxy ...\n{}".format(a, xy))
    return a, xy

# example

a
array([[7, 2, 7],
       [1, 2, 7],
       [3, 4, 3],
       [9, 7, 3]])
# -- xy ...
[(0., 0., 7) (0., 1., 2) (0., 2., 7) (1., 0., 1) (1., 1., 2) (1., 2., 7)
 (2., 0., 3) (2., 1., 4) (2., 2., 3) (3., 0., 9) (3., 1., 7) (3., 2., 3)]

# -- as file for NumPyArrayToTable
(array([[7, 2, 7],
        [1, 2, 7],
        [3, 4, 3],
        [9, 7, 3]]),

XY
 array([(0., 0., 7), (0., 1., 2), (0., 2., 7), (1., 0., 1), (1., 1., 2),
        (1., 2., 7), (2., 0., 3), (2., 1., 4), (2., 2., 3), (3., 0., 9),
        (3., 1., 7), (3., 2., 3)],
       dtype=[('X', '&amp;lt;f8'), ('Y', '&amp;lt;f8'), ('Val', '&amp;lt;i4')]))&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;And my helper script which I use to bring back arrays as featureclasses (points with x, y and z values) or out to csv.&lt;/P&gt;&lt;LI-CODE lang="python"&gt;def save_txt(a, name="arr.txt", sep=", ", dt_hdr=True):
    """Save a NumPy structured/recarray to text.

    Parameters
    ----------
    a : array
        Input array.
    name : filename
        Output filename and path otherwise save to script folder.
    sep : separator
        Column separator, include a space if needed.
    dt_hdr : boolean
        If True, add dtype names to the header of the file.

    """
    a_names = ", ".join(a.dtype.names)
    hdr = ["", a_names][dt_hdr]  # use "" or names from input array
    s = np.array(a.tolist(), dtype=np.unicode_)
    widths = [max([len(i) for i in s[:, j]])
              for j in range(s.shape[1])]
    frmt = sep.join(["%{}s".format(i) for i in widths])
    np.savetxt(name, a, fmt=frmt, header=hdr, comments="")
    print("\nFile saved...")&lt;/LI-CODE&gt;&lt;P&gt;Result&lt;/P&gt;&lt;LI-CODE lang="python"&gt;X, Y, Val
0.0, 0.0, 6
0.0, 1.0, 3
0.0, 2.0, 0
1.0, 0.0, 2
1.0, 1.0, 5
1.0, 2.0, 3
2.0, 0.0, 3
2.0, 1.0, 9
2.0, 2.0, 4
3.0, 0.0, 7
3.0, 1.0, 2
3.0, 2.0, 4&lt;/LI-CODE&gt;&lt;P&gt;Hope you find a few tidbits therein.&lt;/P&gt;&lt;P&gt;glad to see you using numpy.&lt;/P&gt;</description>
    <pubDate>Thu, 11 Nov 2021 20:46:15 GMT</pubDate>
    <dc:creator>DanPatterson</dc:creator>
    <dc:date>2021-11-11T20:46:15Z</dc:date>
    <item>
      <title>Raster to XYZ CSV</title>
      <link>https://community.esri.com/t5/python-questions/raster-to-xyz-csv/m-p/1115993#M62958</link>
      <description>&lt;P&gt;Hi all,&lt;/P&gt;&lt;P&gt;I am trying to improve my python skills, has anyone got some tips to improve this code.&lt;/P&gt;&lt;P&gt;The purpose of this is to quickly as possible convert a single band raster (Elevation) into a CSV table that has the rasters x,y,z values.&lt;/P&gt;&lt;P&gt;Obviously this can also be done with various ESRI tools, but it can take hours for large areas, whereas this code will do it much quicker.&lt;/P&gt;&lt;P&gt;I'm still learning python, any tips would be appreciated.&amp;nbsp; Thanks&lt;/P&gt;&lt;P&gt;Also see attached for code&lt;/P&gt;&lt;P&gt;################################&lt;/P&gt;&lt;P&gt;import arcpy&lt;BR /&gt;from arcpy import env&lt;BR /&gt;import csv,os&lt;BR /&gt;import numpy&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;# Set local variables&lt;BR /&gt;inRaster = arcpy.GetParameterAsText(0)&lt;BR /&gt;csv_filepath = arcpy.GetParameterAsText(1)&lt;BR /&gt;roundValue = int(arcpy.GetParameterAsText(2))&lt;BR /&gt;createPointFC = arcpy.GetParameterAsText(3)&lt;BR /&gt;out_path = arcpy.GetParameterAsText(4)&lt;BR /&gt;out_name = arcpy.GetParameterAsText(5)&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;'''&lt;BR /&gt;# Set Fixed variables for testing&lt;BR /&gt;inRaster = r"D:\Input\Raster_clip.tif"&lt;BR /&gt;csv_filepath = r"D:\Output\Coordinates.csv"&lt;BR /&gt;roundValue = 2&lt;BR /&gt;createPointFC = "true" # false is default&lt;BR /&gt;out_path = r"D:\Output\Working.gdb"&lt;BR /&gt;out_name = "points"&lt;BR /&gt;'''&lt;/P&gt;&lt;P&gt;#variables&lt;BR /&gt;fld_names = ["X", "Y", "Z"] # For point file and CSV headers&lt;BR /&gt;noData = -100000000 #Value for no data to exclude later&lt;/P&gt;&lt;P&gt;# Execute Raster To NumPy Array for Dict of xyz values&lt;BR /&gt;arcpy.AddMessage("Creating raster dictionary...")&lt;BR /&gt;theRaster = inRaster&lt;BR /&gt;ras = arcpy.Raster(theRaster)&lt;BR /&gt;ar = arcpy.RasterToNumPyArray(theRaster, nodata_to_value=noData)&lt;BR /&gt;# Get Cellsize of raster&lt;BR /&gt;cellsize = (ras.meanCellHeight + ras.meanCellWidth) / 2&lt;BR /&gt;# Get XY extent&lt;BR /&gt;xmin = ras.extent.XMin&lt;BR /&gt;ymax = ras.extent.YMax&lt;BR /&gt;# Shift XY to center of cell&lt;BR /&gt;centerX = xmin + (cellsize/2)&lt;BR /&gt;centerY = ymax - (cellsize/2)&lt;BR /&gt;centerXj = centerX&lt;BR /&gt;# Amount of cells&lt;BR /&gt;yheight, xwidth = ar.shape&lt;BR /&gt;# Dictionary of (x,y): values&lt;BR /&gt;d={}&lt;/P&gt;&lt;P&gt;# Loop through X and Y for all cells and add X,Y,Z data to Dictionary&lt;BR /&gt;for j in range(yheight):#74&lt;BR /&gt;for i in range(xwidth):#84&lt;BR /&gt;value = ar.item(j, i)&lt;BR /&gt;if value != noData: # remove No Data values&lt;BR /&gt;rValue = round(value, roundValue)&lt;BR /&gt;rCenterX = round(centerX,roundValue)&lt;BR /&gt;rCenterY = round(centerY,roundValue)&lt;BR /&gt;d[rCenterX, rCenterY] = rValue&lt;BR /&gt;centerX = centerX + cellsize&lt;BR /&gt;centerY = centerY - cellsize&lt;BR /&gt;centerX = centerXj&lt;/P&gt;&lt;P&gt;# Create CSV and populate from Dictionary&lt;BR /&gt;arcpy.AddMessage("Creating CSV...")&lt;BR /&gt;my_dict = d&lt;BR /&gt;with open(csv_filepath, 'w') as csv_file:&lt;BR /&gt;writer = csv.writer(csv_file)&lt;BR /&gt;#writer.writerow(fld_names)&lt;BR /&gt;for key in my_dict.keys():&lt;BR /&gt;newKey = str(key).replace('(', '').replace(')', '')&lt;BR /&gt;csv_file.write("{}, {}\n".format(newKey,my_dict[key]))&lt;BR /&gt;csv_file.close()&lt;/P&gt;&lt;P&gt;# Create Point FC from Dictionary&lt;BR /&gt;if createPointFC == "true":&lt;BR /&gt;arcpy.AddMessage("Creating Point Featureclass...")&lt;BR /&gt;# Execute CreateFeatureclass&lt;BR /&gt;spatial_reference = arcpy.Describe(inRaster).spatialReference&lt;BR /&gt;ptFC = arcpy.CreateFeatureclass_management(out_path, out_name, geometry_type='POINT', has_z='ENABLED', spatial_reference=spatial_reference)&lt;BR /&gt;arcpy.management.AddField(ptFC, "X", "Float")&lt;BR /&gt;arcpy.management.AddField(ptFC, "Y", "Float")&lt;BR /&gt;arcpy.management.AddField(ptFC, "Z", "Float")&lt;BR /&gt;#fc = out_path &amp;amp;"\"&amp;amp; out_name&lt;BR /&gt;#fc = r"D:\Output\Working.gdb\Points"&lt;BR /&gt;fullPath = os.path.join(out_path, out_name)&lt;BR /&gt;with arcpy.da.InsertCursor(fullPath,['SHAPE@X', 'SHAPE@Y', 'SHAPE@Z'] + fld_names ) as c: #+ fld_names&lt;BR /&gt;for x,y in my_dict.keys():&lt;BR /&gt;z = my_dict[x,y]&lt;BR /&gt;shapeXYZ = x,y,z&lt;BR /&gt;c.insertRow((x,y,z,x,y,z))&lt;BR /&gt;del c&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 11 Nov 2021 11:39:19 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/raster-to-xyz-csv/m-p/1115993#M62958</guid>
      <dc:creator>Andrew_Needham</dc:creator>
      <dc:date>2021-11-11T11:39:19Z</dc:date>
    </item>
    <item>
      <title>Re: Raster to XYZ CSV</title>
      <link>https://community.esri.com/t5/python-questions/raster-to-xyz-csv/m-p/1116113#M62962</link>
      <description>&lt;P&gt;Not sure what parts of the script is doing, so just an example for consideration.&lt;/P&gt;&lt;P&gt;Starting with a 2d numpy array and convert it to 2 forms of xyz arrays.&amp;nbsp; The last, a structured array with field names, makes it easier to convert to a csv.&lt;/P&gt;&lt;LI-CODE lang="python"&gt;    a = np.random.randint(0, 10, size=(4, 3))
    a_st = []
    idx = np.indices(a.shape)
    x = idx[0].flatten()
    y = idx[1].flatten()
    vals = a.flatten()
    xy = list(zip(x, y, vals))
    dt = [('X', '&amp;lt;f8'), ('Y', '&amp;lt;f8'), ('Val', '&amp;lt;i4')]
    xy = np.asarray(xy, dtype=dt)
    print("syntax... a\n{!r:}\nxy ...\n{}".format(a, xy))
    return a, xy

# example

a
array([[7, 2, 7],
       [1, 2, 7],
       [3, 4, 3],
       [9, 7, 3]])
# -- xy ...
[(0., 0., 7) (0., 1., 2) (0., 2., 7) (1., 0., 1) (1., 1., 2) (1., 2., 7)
 (2., 0., 3) (2., 1., 4) (2., 2., 3) (3., 0., 9) (3., 1., 7) (3., 2., 3)]

# -- as file for NumPyArrayToTable
(array([[7, 2, 7],
        [1, 2, 7],
        [3, 4, 3],
        [9, 7, 3]]),

XY
 array([(0., 0., 7), (0., 1., 2), (0., 2., 7), (1., 0., 1), (1., 1., 2),
        (1., 2., 7), (2., 0., 3), (2., 1., 4), (2., 2., 3), (3., 0., 9),
        (3., 1., 7), (3., 2., 3)],
       dtype=[('X', '&amp;lt;f8'), ('Y', '&amp;lt;f8'), ('Val', '&amp;lt;i4')]))&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;And my helper script which I use to bring back arrays as featureclasses (points with x, y and z values) or out to csv.&lt;/P&gt;&lt;LI-CODE lang="python"&gt;def save_txt(a, name="arr.txt", sep=", ", dt_hdr=True):
    """Save a NumPy structured/recarray to text.

    Parameters
    ----------
    a : array
        Input array.
    name : filename
        Output filename and path otherwise save to script folder.
    sep : separator
        Column separator, include a space if needed.
    dt_hdr : boolean
        If True, add dtype names to the header of the file.

    """
    a_names = ", ".join(a.dtype.names)
    hdr = ["", a_names][dt_hdr]  # use "" or names from input array
    s = np.array(a.tolist(), dtype=np.unicode_)
    widths = [max([len(i) for i in s[:, j]])
              for j in range(s.shape[1])]
    frmt = sep.join(["%{}s".format(i) for i in widths])
    np.savetxt(name, a, fmt=frmt, header=hdr, comments="")
    print("\nFile saved...")&lt;/LI-CODE&gt;&lt;P&gt;Result&lt;/P&gt;&lt;LI-CODE lang="python"&gt;X, Y, Val
0.0, 0.0, 6
0.0, 1.0, 3
0.0, 2.0, 0
1.0, 0.0, 2
1.0, 1.0, 5
1.0, 2.0, 3
2.0, 0.0, 3
2.0, 1.0, 9
2.0, 2.0, 4
3.0, 0.0, 7
3.0, 1.0, 2
3.0, 2.0, 4&lt;/LI-CODE&gt;&lt;P&gt;Hope you find a few tidbits therein.&lt;/P&gt;&lt;P&gt;glad to see you using numpy.&lt;/P&gt;</description>
      <pubDate>Thu, 11 Nov 2021 20:46:15 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/raster-to-xyz-csv/m-p/1116113#M62962</guid>
      <dc:creator>DanPatterson</dc:creator>
      <dc:date>2021-11-11T20:46:15Z</dc:date>
    </item>
  </channel>
</rss>

