1

My code is throwing the following error:

TypeError: must be str, not float.

It is supposed to use the Int function in Spatial Analyst to do proper rounding instead of truncation. How can I identify my error? I am new to Python and learning as I go. I show below where the error is thrown.

# Name: intrndthm.py
# Description: Converts each cell value of a raster to an integer by proper rounding instead of truncation - will not work for negative values
# Requirements: Spatial Analyst Extension

# Import system modules
import arcpy
from arcpy import env
from arcpy.sa import *

# Set environment settings
env.workspace = "h:/test"

# Set local variables
inRaster = "demtest1.tif"

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Execute Int
outInt = Int(inRaster + 0.5) - error thorwn here. If I use it in the raster calculator it works. If I Use outInt = Int(inRaster) it works but it truncates. 

# Save the output 
outInt.save("h:/test/output/demtest1rnd.tif")
1
  • 1
    Try inRaster = Raster("demtest.tif") and execute again. You have to call Raster after callick spatial analyst. Right now the problem is, you have inRaster as string, you have to convert it to Raster object to use it any other way Dec 18, 2019 at 15:29

1 Answer 1

2

The problem is, you have

inRaster = "demtest1.tif" 

Which is a string:

>>inRaster = "demtest1.tif" 
>>type(inRaster)
<type 'str'>

You should convert it to Raster object, so you can use it in Raster algebra

Eg:

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Set local variables
inRaster = Raster("demtest1.tif")

# Execute Int
outInt = Int(inRaster + 0.5)  

Now you can use it.

If you want it to do it your way. It will have to be a bit different (use Plus function, for adding data) after that call Int function:

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Set local variables
inRaster = "demtest1.tif"

# Execute Int
plus = Plus(inRaster, 0.5)
outInt = Int(plus)
outInt.save(output)  
2
  • This is awesome! Thank you for taking the time to explain this. I have it working now!
    – Todd
    Dec 18, 2019 at 15:51
  • I have found a way to make it work for negative values too: outInt = Con(inRaster < 0, Int(inRaster - 0.5), Int(inRaster + 0.5))
    – Todd
    Dec 18, 2019 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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