# Problem with calculating the total cell values

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.

-
How are your NoData values encoded? – whuber May 16 '13 at 4:16
How can i solve this issue ? – Ja Geo May 16 '13 at 5:01
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

You could use a masked array like this:

``````#Assuming your NoData value is −32768

#OR

#Explicitly set the nodata value

#OR

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
``````
-
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) 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