# Calculate Z Median from 3d line?

How does one calculate the median value of Z from a 3D line?

The Add Surface Information tool in 3D Analyst only does Min,Max and Mean (average), and requires a surface model. (In this case I have one, but all necessary info is in the line, so let's just use that.) Line Statistics can do Median as well as Minority, Majority and a few others, but it doesn't know about 3D lines and only operates on field attributes.

Primary environment is ArcGIS Desktop but I'm open to Gdal/Qgis methods that write results to the source feature class in place (file-gdb).

Desired outcome are lines with a populated Z_Median attribute.

Interpolate shapes using tool from 3d analyst. Run field calculator expression on numeric field type float, parser - Python

``````def getMedian(shp):
aList=[]
part=shp.getPart(0)
n=len(part)
for i in xrange(n):
p=part.getObject(i)
z=p.Z
aList.append(z)
aList.sort()
return aList[n/2]
``````

To call it use:

``````getMedian(!Shape!)
``````

It will work on a single part 3D polylines

• This is near perfect, thanks (though indentation screwed me up for awhile. I'd put aList.append in parent). I changed it to use `numpy.median()` so I didn't have to add logic to handle when the list has even number of items. Those with ArcGIS Pro can use `statistics.median()` instead ('cause python 3). Good python + median reading: stackoverflow.com/questions/24101524/… Commented Jan 19, 2016 at 18:28
• This will fail on a polygon interior ring ("AttributeError: 'NoneType' object has no attribute 'Z'"). This seems to work: `p=part.getObject(i); if p: z=p.Z`. Commented Feb 10, 2016 at 21:55

Try using the Add Z Information tool.

• It's not appreciably different from Add Surface Information tool, providing only min,max and mean statistics. Commented Jan 18, 2016 at 23:02