Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

aa= arcpy.RasterToNumPyArray("water_depth")

sum = numpy.sum(aa)

print sum

-2933737

Why I am getting negative values ? In my raster there is no any negative depth.

share|improve this question
3  
How are your NoData values encoded? –  whuber May 16 '13 at 4:16
    
How can i solve this issue ? –  Jaya Pudashine May 16 '13 at 5:01
1  
To find out your NoData value, right click the raster in the ArcMap table of contents, select Properties... click the Source tab and scroll down to find NoData value (it's in the Raster Information group). –  Luke May 16 '13 at 6:21

1 Answer 1

You could use a masked array like this:

#Assuming your NoData value is −32768
aa=numpy.ma.MaskedArray(arcpy.RasterToNumPyArray("water_depth"))
aa.mask=(aa==-32768)

#OR

#Explicitly set the nodata value
aa=numpy.ma.MaskedArray(arcpy.RasterToNumPyArray("water_depth",nodata_to_value=-999))
aa.mask=(aa==-999)

#OR

#Or just mask anything negative
aa=numpy.ma.MaskedArray(arcpy.RasterToNumPyArray("water_depth"))
aa.mask=(aa<0)

sum = aa.sum()

print sum

It might be a an integer overflow problem as @whuber suggests if the sum is greater than the bounds of a signed 32bit integer (numpy will cast smaller datatypes to bigger if required when summing, but won't cast int32 to int64 automatically). Consider the following code:

a=numpy.array([2**(16-1)-1,2**(16-1)-1],dtype=numpy.int16) # signed 16bit int (-32768:32767)
b=numpy.array([2**(32-1)-1,2**(32-1)-1],dtype=numpy.int32) # signed 32bit int (-2147483648:2147483647)

print a
print b
#  Prints:
# [32767 32767]
# [2147483647 2147483647]

# make them overflow
print a+1
print b+1
#  Prints:
# [-32768 -32768]
# [-2147483648 -2147483648]

print a.sum()
print (a.sum()).dtype # automatically cast to int32
# Prints:
# 65534
# int32

print b.sum()           # int32 overflows
print (b.sum()).dtype   # instead of being cast to int64
# Prints:
# -2
# int32

print b.astype(numpy.int64).sum() # explicitly cast to int64
# Prints:
# 4294967294
share|improve this answer
1  
There's also a nodata_to_value parameter in the RasterToNumPyArray function. This way you wouldn't need to look up the NoData value every time. –  dmahr May 16 '13 at 13:37
1  
(+1) IF the problem is a negative code for NoData, then--because the OP asserts there should be no negative values in the raster--it would be more reliable to mask out all negative values. But there are other potential causes of this problem, such as overflow of signed integer addition. –  whuber May 16 '13 at 14:13
    
@dmahr thanks, I've incorporated your comments in the answer –  Luke May 17 '13 at 0:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.