├── 5656.ipynb ├── 克里金插值和IDW插值 ├── README.md ├── pmdata.xlsx ├── shp │ ├── 江苏省_行政边界.dbf │ ├── 江苏省_行政边界.shp │ ├── 江苏省_行政边界.shx │ ├── 江苏省_行政边界.prj │ └── 江苏省_行政边界.tdb ├── kriging.py ├── idw.py └── RBF插值.py ├── README.md ├── 03设置环境 ├── SetEnvironment.py └── ScratchWorkspace.py ├── 05处理数据集 ├── FieldMappings.py └── TableBatch.py ├── 01使用函数 ├── 03描述数据 │ └── Describe.py ├── 04列出数据 │ ├── 06ListFields.py │ ├── 03ListDatasets.py │ ├── 04ListFeatureClasses.py │ ├── 02ListFiles.py │ ├── 05ListTables.py │ ├── 01ListWorkspaces.py │ └── 07AddFields.py ├── 01常规函数 │ ├── TestSchemaLock.py │ ├── CreateScratchName.py │ ├── CreateUniqueName.py │ └── Exists.py ├── 02字段 │ ├── AddFieldDelimiters.py │ └── ValidateFieldName.py ├── 06进度对话框 │ ├── SetProgressor.gif │ └── SetProgressor │ │ ├── SetProgressor.tbx │ │ └── SetProgressor.py ├── 05获取和设置参数 │ ├── GetParameter │ │ ├── GetParameter.tbx │ │ └── TestGetParameter.py │ ├── TestGetParameter.py │ └── TestCustomGetParameter.py └── 07消息和错误处理 │ ├── TestAddMessage │ ├── AddMessage.tbx │ └── AddMessage.py │ └── GetMessages.py ├── 06访问地理数据 ├── TestFeatureset.py ├── SpatialReference.py ├── GetShptype.py └── TestSQL.py ├── 07使用游标 ├── 读取几何 │ ├── ReadHollowPolygon.py │ ├── ReadPoint.py │ ├── ReadPolygon.py │ ├── ReadMultiPoint.py │ ├── ReadPolyline.py │ └── ReadMultiPart.py ├── 写入几何 │ ├── CreateHollowPolygon1.py │ ├── CreatePoint1.py │ ├── CreatePolygon1.py │ ├── CreateMultiPoint1.py │ ├── CreatePolyline1.py │ └── CreateMultiPart1.py └── TestCursor.py ├── boripoming-geographic_data_visualization-master.zip ├── .idea └── vcs.xml ├── ascii.py ├── 02使用类 ├── TestEnv.py ├── TestExecuteClass.py └── TestCursor10.0.py ├── bands_merge.py ├── arcpy_raster_example.py ├── 04错误与异常处理 └── TestError.py ├── Batch_reprojection.py └── Batch_rename_tif.py /5656.ipynb: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /克里金插值和IDW插值/README.md: -------------------------------------------------------------------------------- 1 | # geo -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python_c123 2 | 3 | python_ arcgis运用 4 | -------------------------------------------------------------------------------- /03设置环境/SetEnvironment.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/03设置环境/SetEnvironment.py -------------------------------------------------------------------------------- /05处理数据集/FieldMappings.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/05处理数据集/FieldMappings.py -------------------------------------------------------------------------------- /克里金插值和IDW插值/pmdata.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/克里金插值和IDW插值/pmdata.xlsx -------------------------------------------------------------------------------- /01使用函数/03描述数据/Describe.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/03描述数据/Describe.py -------------------------------------------------------------------------------- /06访问地理数据/TestFeatureset.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/06访问地理数据/TestFeatureset.py -------------------------------------------------------------------------------- /01使用函数/04列出数据/06ListFields.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/04列出数据/06ListFields.py -------------------------------------------------------------------------------- /06访问地理数据/SpatialReference.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/06访问地理数据/SpatialReference.py -------------------------------------------------------------------------------- /克里金插值和IDW插值/shp/江苏省_行政边界.dbf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/克里金插值和IDW插值/shp/江苏省_行政边界.dbf -------------------------------------------------------------------------------- /克里金插值和IDW插值/shp/江苏省_行政边界.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/克里金插值和IDW插值/shp/江苏省_行政边界.shp -------------------------------------------------------------------------------- /克里金插值和IDW插值/shp/江苏省_行政边界.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/克里金插值和IDW插值/shp/江苏省_行政边界.shx -------------------------------------------------------------------------------- /01使用函数/01常规函数/TestSchemaLock.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/01常规函数/TestSchemaLock.py -------------------------------------------------------------------------------- /01使用函数/04列出数据/03ListDatasets.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/04列出数据/03ListDatasets.py -------------------------------------------------------------------------------- /01使用函数/01常规函数/CreateScratchName.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/01常规函数/CreateScratchName.py -------------------------------------------------------------------------------- /01使用函数/01常规函数/CreateUniqueName.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/01常规函数/CreateUniqueName.py -------------------------------------------------------------------------------- /01使用函数/02字段/AddFieldDelimiters.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/02字段/AddFieldDelimiters.py -------------------------------------------------------------------------------- /01使用函数/02字段/ValidateFieldName.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/02字段/ValidateFieldName.py -------------------------------------------------------------------------------- /01使用函数/06进度对话框/SetProgressor.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/06进度对话框/SetProgressor.gif -------------------------------------------------------------------------------- /07使用游标/读取几何/ReadHollowPolygon.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/07使用游标/读取几何/ReadHollowPolygon.py -------------------------------------------------------------------------------- /07使用游标/写入几何/CreateHollowPolygon1.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/07使用游标/写入几何/CreateHollowPolygon1.py -------------------------------------------------------------------------------- /01使用函数/04列出数据/04ListFeatureClasses.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/04列出数据/04ListFeatureClasses.py -------------------------------------------------------------------------------- /01使用函数/05获取和设置参数/GetParameter/GetParameter.tbx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/05获取和设置参数/GetParameter/GetParameter.tbx -------------------------------------------------------------------------------- /01使用函数/06进度对话框/SetProgressor/SetProgressor.tbx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/06进度对话框/SetProgressor/SetProgressor.tbx -------------------------------------------------------------------------------- /01使用函数/07消息和错误处理/TestAddMessage/AddMessage.tbx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/01使用函数/07消息和错误处理/TestAddMessage/AddMessage.tbx -------------------------------------------------------------------------------- /01使用函数/04列出数据/02ListFiles.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.env.workspace = os.getcwd() 4 | for py_file in arcpy.ListFiles("*.py"): 5 | print py_file 6 | -------------------------------------------------------------------------------- /boripoming-geographic_data_visualization-master.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongyi1996/Python_chazhi/HEAD/boripoming-geographic_data_visualization-master.zip -------------------------------------------------------------------------------- /克里金插值和IDW插值/shp/江苏省_行政边界.prj: -------------------------------------------------------------------------------- 1 | GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]] -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ascii.py: -------------------------------------------------------------------------------- 1 | import arcpy 2 | import os 3 | raster_path='E:/vic_output/sm1_tif/' 4 | out_path='E:/vic_output/sm1_ascii/' 5 | files = [f for f in os.listdir(raster_path) if f.endswith('TIF')] 6 | for file in files: 7 | arcpy.RasterToASCII_conversion(raster_path+file, out_path+file+'.txt') 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /01使用函数/01常规函数/Exists.py: -------------------------------------------------------------------------------- 1 | import arcpy,os 2 | scratch_name = arcpy.CreateUniqueName("temp.shp",arcpy.env.scratchFolder) 3 | print arcpy.Exists(scratch_name) 4 | scratch_filename = os.path.basename(scratch_name) 5 | arcpy.CreateFeatureclass_management(arcpy.env.scratchFolder,scratch_filename,"POLYGON") 6 | print arcpy.Exists(scratch_name) 7 | -------------------------------------------------------------------------------- /02使用类/TestEnv.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | print "Not defined scratchWorkspace:" 4 | print arcpy.env.scratchWorkspace 5 | 6 | print("Defined folder as scratchWorkspace:") 7 | desktopFolder = os.path.join(os.path.expanduser("~"), 'Desktop') 8 | arcpy.env.scratchWorkspace = desktopFolder 9 | print(arcpy.env.scratchWorkspace) 10 | -------------------------------------------------------------------------------- /克里金插值和IDW插值/shp/江苏省_行政边界.tdb: -------------------------------------------------------------------------------- 1 | [General] 2 | VERSION=1 3 | DATATYPE=2 4 | TASKNAME=\x6c5f\x82cf\x7701_\x884c\x653f\x8fb9\x754c 5 | CREATETIME=@Variant(\0\0\0\x10\0\0\0\0\xff\xff\xff\xff\xff) 6 | SUCCESS=true 7 | PROIMGURL=://Resources/vector_map.png 8 | BOUNDS="@Variant(\0\0\0\x14@]\x16\xceVb]\x95@>\xc2\x99\x1bQ\xe5_@\x16uYeF\x9e\xc0@\x11\x86\xbf}i\x9a,)" 9 | -------------------------------------------------------------------------------- /01使用函数/05获取和设置参数/TestGetParameter.py: -------------------------------------------------------------------------------- 1 | import arcpy 2 | 3 | print(arcpy.GetParameterCount("Buffer_analysis")) 4 | params = arcpy.GetParameterInfo("Buffer_analysis") 5 | i = 0 6 | for param in params: 7 | print("Name: {}, Type: {}, Value: {}".format( 8 | param.name, param.parameterType, param.value)) 9 | print(arcpy.GetParameterValue("Buffer_analysis", i)) 10 | i = i + 1 -------------------------------------------------------------------------------- /bands_merge.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.env.workspace = r'D:\huangtu\8km_data\8KM_NDVI\isnull_nodata' 4 | 5 | 6 | # list all folders in a directory 7 | 8 | rasters = arcpy.ListRasters("*.tif") 9 | for raster in rasters: 10 | print raster 11 | 12 | name = r"D:\huangtu\8km_data\8KM_NDVI\NDVI82_15.tif" 13 | arcpy.CompositeBands_management(rasters, name) 14 | 15 | print "Processing complete" 16 | -------------------------------------------------------------------------------- /06访问地理数据/GetShptype.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.CreateFeatureclass_management(os.getcwd(), "TestGetShpPoint.shp", "POINT") 4 | arcpy.CreateFeatureclass_management(os.getcwd(), "TestGetShpPolygon.shp", "POLYGON") 5 | descPoint = arcpy.Describe(os.getcwd() + os.sep + "TestGetShpPoint.shp") 6 | print descPoint.shapeType 7 | descPolygon = arcpy.Describe(os.getcwd() + os.sep + "TestGetShpPolygon.shp") 8 | print descPolygon.shapeType 9 | -------------------------------------------------------------------------------- /01使用函数/05获取和设置参数/TestCustomGetParameter.py: -------------------------------------------------------------------------------- 1 | import arcpy 2 | 3 | arcpy.ImportToolbox(r"C:\Users\Admin\Desktop\GetParameter\GetParameter.tbx") 4 | print(arcpy.GetParameterCount("TestGetParameter")) 5 | params = arcpy.GetParameterInfo("TestGetParameter") 6 | i = 0 7 | for param in params: 8 | print("Name: {}, Type: {}, Value: {}".format( 9 | param.name.encode('gb2312'), param.parameterType, param.value)) 10 | print(arcpy.GetParameterValue("TestGetParameter", i)) 11 | i = i + 1 12 | -------------------------------------------------------------------------------- /01使用函数/04列出数据/05ListTables.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | for i in range(5): 4 | arcpy.CreateTable_management(os.getcwd(), "a" + str(i)) 5 | arcpy.CreateTable_management(os.getcwd(), "b" + str(i) + ".dbf") 6 | arcpy.env.workspace = os.getcwd() 7 | print "These are all tables:" 8 | for table in arcpy.ListTables(): 9 | print table 10 | print "These are all dbfTables:" 11 | for table in arcpy.ListTables("", "dBASE"): 12 | print table 13 | for table in arcpy.ListTables(): 14 | arcpy.Delete_management(os.getcwd() + os.sep + table) 15 | -------------------------------------------------------------------------------- /01使用函数/07消息和错误处理/TestAddMessage/AddMessage.py: -------------------------------------------------------------------------------- 1 | import arcpy 2 | arcpy.AddMessage("This is a Message!") 3 | arcpy.AddWarning("This is an Warning!") 4 | arcpy.AddError("This is an Error!") 5 | arcpy.AddIDMessage("ERROR", 12, "This is an IDMessage!") 6 | try: 7 | result = arcpy.GetCount_management("c:/data/rivers.shp") 8 | except: 9 | # Return Geoprocessing tool specific errors 10 | # 11 | for msg in range(0, arcpy.GetMessageCount()): 12 | if arcpy.GetSeverity(msg) == 2: 13 | arcpy.AddReturnMessage(msg) 14 | 15 | 16 | -------------------------------------------------------------------------------- /02使用类/TestExecuteClass.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.SetSeverityLevel(1) 4 | # Test ExecuteError 5 | try: 6 | arcpy.GetCount_management("") 7 | except arcpy.ExecuteError: 8 | print(arcpy.GetMessages(2)) 9 | 10 | # Test ExecuteWarning 11 | try: 12 | arcpy.CreateFeatureclass_management(os.getcwd(), "TestExecuteShp.shp") 13 | arcpy.DeleteFeatures_management(os.getcwd() + os.sep + "TestExecuteShp.shp") 14 | except arcpy.ExecuteWarning: 15 | print(arcpy.GetMessages(1)) 16 | arcpy.Delete_management(os.getcwd() + os.sep + "TestExecuteShp.shp") 17 | -------------------------------------------------------------------------------- /07使用游标/写入几何/CreatePoint1.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | arcpy.CreateFeatureclass_management(os.getcwd(), "TestCreatePoint1.shp", "POINT", spatial_reference=spatialReference) 5 | in_fc = os.getcwd() + os.sep + "TestCreatePoint1.shp" 6 | cursor = arcpy.da.InsertCursor(in_fc, ["SHAPE@"]) 7 | point1 = [(77.4349451, 37.5408265)] 8 | point2 = [(77.4349451, 35.7780943)] 9 | point3 = [(78.6384349, 35.7780943)] 10 | point4 = [(78.6384349, 37.5408265)] 11 | cursor.insertRow(point1) 12 | cursor.insertRow(point2) 13 | cursor.insertRow(point3) 14 | cursor.insertRow(point4) 15 | del cursor 16 | -------------------------------------------------------------------------------- /01使用函数/05获取和设置参数/GetParameter/TestGetParameter.py: -------------------------------------------------------------------------------- 1 | import arcpy 2 | # Get the spatial reference from the tool dialog. 3 | txt_param = arcpy.GetParameterAsText(1) 4 | spatial_ref = arcpy.GetParameter(0) 5 | option_param = arcpy.GetParameterAsText(2) 6 | 7 | # Display ArgumentCount 8 | arcpy.AddMessage("ArgumentCount is: {0}".format(arcpy.GetArgumentCount())) 9 | # Display txt_param 10 | arcpy.AddMessage("txt_param is: {0}".format(txt_param)) 11 | # Display the Spatial Reference properties 12 | arcpy.AddMessage("Name is: {0}".format(spatial_ref.name)) 13 | arcpy.AddMessage("Type is: {0}".format(spatial_ref.type)) 14 | arcpy.AddMessage("Factory code is: {0}".format(spatial_ref.factoryCode)) 15 | -------------------------------------------------------------------------------- /05处理数据集/TableBatch.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.CreateFolder_management(os.getcwd(), "TestFcBatch") 4 | in_folder = os.getcwd() + os.sep + "TestFcBatch" 5 | for i in range(20): 6 | arcpy.CreateTable_management(in_folder, "tt" + str(i) + ".dbf") 7 | arcpy.env.workspace = in_folder 8 | table_list = arcpy.ListTables() 9 | for table in table_list: 10 | print table 11 | arcpy.AddField_management(table, "TableName", "TEXT") 12 | rows = arcpy.InsertCursor(table) 13 | for i in range(1, 26): 14 | row = rows.newRow() 15 | row.setValue('TableName', table) 16 | rows.insertRow(row) 17 | del row 18 | del rows 19 | # arcpy.Delete_management(in_folder) 20 | -------------------------------------------------------------------------------- /07使用游标/写入几何/CreatePolygon1.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | arcpy.CreateFeatureclass_management(os.getcwd(), "TestCreatePolygon1.shp", "POLYGON", 5 | spatial_reference=spatialReference) 6 | in_fc = os.getcwd() + os.sep + "TestCreatePolygon1.shp" 7 | cursor = arcpy.da.InsertCursor(in_fc, ["SHAPE@"]) 8 | point1 = arcpy.Point(77.4349451, 37.5408265) 9 | point2 = arcpy.Point(77.4349451, 35.7780943) 10 | point3 = arcpy.Point(78.6384349, 35.7780943) 11 | point4 = arcpy.Point(78.6384349, 37.5408265) 12 | polygon = arcpy.Polygon(arcpy.Array([point1, point2, point3, point4])) 13 | cursor.insertRow([polygon]) 14 | del cursor 15 | -------------------------------------------------------------------------------- /07使用游标/写入几何/CreateMultiPoint1.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | arcpy.CreateFeatureclass_management(os.getcwd(), "TestCreateMultiPoint1.shp", "MULTIPOINT", 5 | spatial_reference=spatialReference) 6 | in_fc = os.getcwd() + os.sep + "TestCreateMultiPoint1.shp" 7 | cursor = arcpy.da.InsertCursor(in_fc, ["SHAPE@"]) 8 | point1 = (77.4349451, 37.5408265) 9 | point2 = (77.4349451, 35.7780943) 10 | point3 = (78.6384349, 35.7780943) 11 | point4 = (78.6384349, 37.5408265) 12 | multiPoint1 = (point1, point2) 13 | multiPoint2 = (point3, point4) 14 | cursor.insertRow([multiPoint1]) 15 | cursor.insertRow([multiPoint2]) 16 | del cursor 17 | -------------------------------------------------------------------------------- /07使用游标/读取几何/ReadPoint.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | out_fc = os.getcwd() + os.sep + "TestReadPoint.shp" 5 | point1 = arcpy.Point(77.434, 37.540) 6 | point2 = arcpy.Point(77.434, 35.778) 7 | point3 = arcpy.Point(78.638, 35.778) 8 | point4 = arcpy.Point(78.638, 37.540) 9 | point_list = [point1, point2, point3, point4] 10 | pointGeometryList = [] 11 | for point in point_list: 12 | pointGeometryList.append(arcpy.PointGeometry(point)) 13 | arcpy.CopyFeatures_management(pointGeometryList, out_fc) 14 | arcpy.DefineProjection_management(out_fc, spatialReference) 15 | 16 | with arcpy.da.SearchCursor(out_fc, ["SHAPE@XY"]) as cursor: 17 | for row in cursor: 18 | print row[0] 19 | -------------------------------------------------------------------------------- /07使用游标/读取几何/ReadPolygon.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | out_fc = os.getcwd() + os.sep + "TestReadPolygon.shp" 5 | point1 = arcpy.Point(77.4349451, 37.5408265) 6 | point2 = arcpy.Point(77.4349451, 35.7780943) 7 | point3 = arcpy.Point(78.6384349, 35.7780943) 8 | point4 = arcpy.Point(78.6384349, 37.5408265) 9 | polygon = arcpy.Polygon(arcpy.Array([point1, point2, point3, point4])) 10 | arcpy.CopyFeatures_management(polygon, out_fc) 11 | arcpy.DefineProjection_management(out_fc, spatialReference) 12 | 13 | with arcpy.da.SearchCursor(out_fc, ["OID@", "SHAPE@"]) as cursor: 14 | for row in cursor: 15 | print "Feature {0}".format(row[0]) 16 | for array in row[1]: 17 | for pnt in array: 18 | print pnt.X, pnt.Y 19 | -------------------------------------------------------------------------------- /07使用游标/读取几何/ReadMultiPoint.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | out_fc = os.getcwd() + os.sep + "TestReadMultiPoint.shp" 5 | point1 = arcpy.Point(77.434, 37.540) 6 | point2 = arcpy.Point(77.434, 35.778) 7 | point3 = arcpy.Point(78.638, 35.778) 8 | point4 = arcpy.Point(78.638, 37.540) 9 | multiPoint1 = arcpy.Multipoint(arcpy.Array([point1, point2])) 10 | multiPoint2 = arcpy.Multipoint(arcpy.Array([point3, point4])) 11 | features = [multiPoint1, multiPoint2] 12 | arcpy.CopyFeatures_management(features, out_fc) 13 | arcpy.DefineProjection_management(out_fc, spatialReference) 14 | 15 | with arcpy.da.SearchCursor(out_fc, ["OID@", "SHAPE@"]) as cursor: 16 | for row in cursor: 17 | print "Feature {0}".format(row[0]) 18 | for pnt in row[1]: 19 | print pnt.X, pnt.Y 20 | -------------------------------------------------------------------------------- /03设置环境/ScratchWorkspace.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | print "Not defined scratchWorkspace:" 4 | print arcpy.env.scratchWorkspace 5 | print arcpy.env.scratchFolder 6 | print arcpy.env.scratchGDB 7 | 8 | print "Defined folder as scratchWorkspace:" 9 | desktopFolder = os.path.join(os.path.expanduser("~"), 'Desktop') 10 | arcpy.env.scratchWorkspace = desktopFolder 11 | print arcpy.env.scratchWorkspace 12 | print arcpy.env.scratchFolder 13 | print arcpy.env.scratchGDB 14 | 15 | print "Defined GDB as scratchWorkspace:" 16 | arcpy.CreateFileGDB_management(desktopFolder, "TestScratchWorkspace.gdb") 17 | arcpy.env.scratchWorkspace = desktopFolder + os.sep + "TestScratchWorkspace.gdb" 18 | print arcpy.env.scratchWorkspace 19 | print arcpy.env.scratchFolder 20 | print arcpy.env.scratchGDB 21 | arcpy.Delete_management(desktopFolder + os.sep + "TestScratchWorkspace.gdb") 22 | -------------------------------------------------------------------------------- /arcpy_raster_example.py: -------------------------------------------------------------------------------- 1 | 2 | import arcpy 3 | arcpy.CheckOutExtension("spatial") 4 | 5 | arcpy.env.workspace = r"E:\my_data\data"#���ù����ռ� 6 | inRas = arcpy.Raster("test.tif")desc = arcpy.Describe(inRas)#դ�����������Ϣ 7 | sr = desc.SpatialReference#��ȡ�ռ�ο� 8 | cell_size = inRas.meanCellWidth#һ��դ��Ϊ�����Σ����դ��ߴ���meanCellWidth��ʾlowerLeft = arcpy.Point(inRas.extent.XMin, inRas.extent.YMin) 9 | lowerLeft = arcpy.Point(inRas.extent.XMin, inRas.extent.YMin)#��ȡ���½ǵ����� 10 | Raster_Array = arcpy.RasterToNumPyArray(inRas)#��դ��������飬һ��д�㷨�Ļ�������ô�� 11 | row = DEM_Array.shape[0]#դ������ 12 | col = DEM_Array.shape[1]#դ������ 13 | #������Raster_Arrayд��դ������ 14 | out_raster = arcpy.NumPyArrayToRaster(Raster_Array, lowerLeft, cell_size, cell_size, -9999) 15 | arcpy.DefineProjection_management(out_raster, sr)#д��ռ�ο� 16 | out_raster.save("shuchu.tif")#���������� 17 | -------------------------------------------------------------------------------- /01使用函数/04列出数据/01ListWorkspaces.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.CreatePersonalGDB_management(os.getcwd(), "testListWorkspaces0.mdb") 4 | arcpy.CreatePersonalGDB_management(os.getcwd(), "testListWorkspaces1.mdb") 5 | arcpy.CreateFolder_management(os.getcwd(), "testListWorkspaces2") 6 | arcpy.CreateFileGDB_management(os.getcwd(), "testListWorkspaces3.gdb") 7 | arcpy.CreateFileGDB_management(os.getcwd(), "testListWorkspaces4.gdb") 8 | arcpy.env.workspace = os.getcwd() 9 | workSpaces = arcpy.ListWorkspaces() 10 | print "This is all workSpaces:" 11 | workSpaces = arcpy.ListWorkspaces() 12 | for workSpace in workSpaces: 13 | print workSpace 14 | print "This is all gdb:" 15 | workSpaces = arcpy.ListWorkspaces("*", "FileGDB") 16 | for workSpace in workSpaces: 17 | print workSpace 18 | 19 | workSpaces = arcpy.ListWorkspaces() 20 | for workSpace in workSpaces: 21 | arcpy.Delete_management(workSpace) 22 | -------------------------------------------------------------------------------- /07使用游标/写入几何/CreatePolyline1.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | arcpy.CreateFeatureclass_management(os.getcwd(), "TestCreatePolyline1.shp", "POLYLINE", 5 | spatial_reference=spatialReference) 6 | in_fc = os.getcwd() + os.sep + "TestCreatePolyline1.shp" 7 | cursor = arcpy.da.InsertCursor(in_fc, ["SHAPE@"]) 8 | point1 = arcpy.Point(77.4349451, 37.5408265) 9 | point2 = arcpy.Point(77.4349451, 35.7780943) 10 | point3 = arcpy.Point(78.6384349, 35.7780943) 11 | point4 = arcpy.Point(78.6384349, 37.5408265) 12 | polyLine1 = arcpy.Polyline(arcpy.Array([point1, point2])) 13 | polyLine2 = arcpy.Polyline(arcpy.Array([point2, point3])) 14 | polyLine3 = arcpy.Polyline(arcpy.Array([point3, point4])) 15 | polyLine4 = arcpy.Polyline(arcpy.Array([point4, point1])) 16 | cursor.insertRow([polyLine1]) 17 | cursor.insertRow([polyLine2]) 18 | cursor.insertRow([polyLine3]) 19 | cursor.insertRow([polyLine4]) 20 | del cursor 21 | -------------------------------------------------------------------------------- /04错误与异常处理/TestError.py: -------------------------------------------------------------------------------- 1 | class NoFeatures(Exception): 2 | pass 3 | 4 | 5 | import arcpy 6 | import os 7 | import sys 8 | import traceback 9 | 10 | try: 11 | ## part1 Test ExecuteError 12 | #arcpy.GetCount_management("") 13 | 14 | ## part2 Test raise 15 | # arcpy.CreateFeatureclass_management(os.getcwd(), "testError.shp") 16 | # result = arcpy.GetCount_management(os.getcwd() + os.sep + "testError.shp") 17 | # if result[0] == "0": 18 | # raise NoFeatures() 19 | # arcpy.Delete_management(os.getcwd() + os.sep + "testError.shp") 20 | 21 | ## part3 Test traceback 22 | x = "a" + 1 23 | except arcpy.ExecuteError: 24 | msgs = arcpy.GetMessages(2) 25 | print(msgs) 26 | except NoFeatures: 27 | print "There is no features!" 28 | except: 29 | tb = sys.exc_info()[2] 30 | tbinfo = traceback.format_tb(tb)[0] 31 | pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) 32 | print(pymsg) 33 | -------------------------------------------------------------------------------- /07使用游标/写入几何/CreateMultiPart1.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | arcpy.CreateFeatureclass_management(os.getcwd(), "TestCreateMultiPart1.shp", "POLYGON", 5 | spatial_reference=spatialReference) 6 | in_fc = os.getcwd() + os.sep + "TestCreateMultiPart1.shp" 7 | cursor = arcpy.da.InsertCursor(in_fc, ["SHAPE@"]) 8 | point1 = arcpy.Point(77.4349451, 37.5408265) 9 | point2 = arcpy.Point(77.4349451, 35.7780943) 10 | point3 = arcpy.Point(78.6384349, 35.7780943) 11 | point4 = arcpy.Point(78.6384349, 37.5408265) 12 | point5 = arcpy.Point(78.8349451, 36.6408265) 13 | point6 = arcpy.Point(78.8349451, 36.0780943) 14 | point7 = arcpy.Point(79.2384349, 36.0780943) 15 | point8 = arcpy.Point(79.2384349, 36.6408265) 16 | polygon1 = arcpy.Array([point1, point2, point3, point4]) 17 | polygon2 = arcpy.Array([point5, point6, point7, point8]) 18 | multiPart = arcpy.Polygon(arcpy.Array([polygon1, polygon2])) 19 | cursor.insertRow([multiPart]) 20 | del cursor 21 | -------------------------------------------------------------------------------- /06访问地理数据/TestSQL.py: -------------------------------------------------------------------------------- 1 | import arcpy, os, random 2 | 3 | point_list = [] 4 | for i in range(0, 100): 5 | point_list.append(arcpy.Point(random.randint(73, 135), random.randint(0, 90))) 6 | out_fc = os.getcwd() + os.sep + "TestSQLPoint.shp" 7 | pointGeometryList = [] 8 | for point in point_list: 9 | pointGeometryList.append(arcpy.PointGeometry(point)) 10 | arcpy.CopyFeatures_management(pointGeometryList, out_fc) 11 | spatialReference = arcpy.SpatialReference(4326) 12 | arcpy.DefineProjection_management(out_fc, spatialReference) 13 | arcpy.AddField_management(out_fc, "Y", "SHORT") 14 | arcpy.CalculateField_management(out_fc, "Y", "!shape.centroid.Y!", "PYTHON_9.3") 15 | field_delimiters = arcpy.AddFieldDelimiters(os.getcwd(), "Y") 16 | arcpy.AddField_management(out_fc, "CLASS", "TEXT", field_length=50) 17 | where_clause = field_delimiters + "<=30" 18 | with arcpy.da.UpdateCursor(out_fc, ["CLASS"], where_clause) as cursor: 19 | for row in cursor: 20 | row[0] = "Low latitude" 21 | cursor.updateRow(row) 22 | -------------------------------------------------------------------------------- /07使用游标/读取几何/ReadPolyline.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | out_fc = os.getcwd() + os.sep + "TestReadPolyline.shp" 5 | point1 = arcpy.Point(77.4349451, 37.5408265) 6 | point2 = arcpy.Point(77.4349451, 35.7780943) 7 | point3 = arcpy.Point(78.6384349, 35.7780943) 8 | point4 = arcpy.Point(78.6384349, 37.5408265) 9 | polyLine1 = arcpy.Polyline(arcpy.Array([point1, point2])) 10 | polyLine2 = arcpy.Polyline(arcpy.Array([point2, point3])) 11 | polyLine3 = arcpy.Polyline(arcpy.Array([point3, point4])) 12 | polyLine4 = arcpy.Polyline(arcpy.Array([point4, point1])) 13 | features = [polyLine1, polyLine2, polyLine3, polyLine4] 14 | arcpy.CopyFeatures_management(features, out_fc) 15 | arcpy.DefineProjection_management(out_fc, spatialReference) 16 | 17 | with arcpy.da.SearchCursor(out_fc, ["OID@", "SHAPE@"]) as cursor: 18 | for row in cursor: 19 | print "Feature {0}".format(row[0]) 20 | for array in row[1]: 21 | for pnt in array: 22 | print pnt.X, pnt.Y 23 | -------------------------------------------------------------------------------- /07使用游标/读取几何/ReadMultiPart.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | spatialReference = arcpy.SpatialReference(4326) 4 | out_fc = os.getcwd() + os.sep + "TestReadMultiPart.shp" 5 | point1 = arcpy.Point(77.4349451, 37.5408265) 6 | point2 = arcpy.Point(77.4349451, 35.7780943) 7 | point3 = arcpy.Point(78.6384349, 35.7780943) 8 | point4 = arcpy.Point(78.6384349, 37.5408265) 9 | point5 = arcpy.Point(78.8349451, 36.6408265) 10 | point6 = arcpy.Point(78.8349451, 36.0780943) 11 | point7 = arcpy.Point(79.2384349, 36.0780943) 12 | point8 = arcpy.Point(79.2384349, 36.6408265) 13 | polygon1 = arcpy.Array([point1, point2, point3, point4]) 14 | polygon2 = arcpy.Array([point5, point6, point7, point8]) 15 | multiPart = arcpy.Polygon(arcpy.Array([polygon1, polygon2])) 16 | arcpy.CopyFeatures_management(multiPart, out_fc) 17 | arcpy.DefineProjection_management(out_fc, spatialReference) 18 | 19 | with arcpy.da.SearchCursor(out_fc, ["OID@", "SHAPE@"]) as cursor: 20 | for row in cursor: 21 | print "Feature {0}".format(row[0]) 22 | partnum = 0 23 | for part in row[1]: 24 | partnum += 1 25 | print "Part{0}:".format(partnum) 26 | for pnt in part: 27 | print pnt.X, pnt.Y 28 | -------------------------------------------------------------------------------- /01使用函数/04列出数据/07AddFields.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.CreateFeatureclass_management(os.getcwd(), "testAddFields.shp") 4 | in_fc = os.getcwd() + os.sep + "testAddFields.shp" 5 | in_field_csv = os.getcwd() + os.sep + "a.csv" 6 | try: 7 | with open(in_field_csv) as f: 8 | f.readline() 9 | lines = f.readlines() 10 | for line in lines: 11 | field = line.rstrip("\n").split(",") 12 | print field 13 | if field[1].upper() == "SINGLE" or field[1].upper() == "FLOAT" or field[1].upper() == "DOUBLE": 14 | arcpy.AddField_management(in_fc, field[0], field[1], field[3], field[4]) 15 | elif field[1].upper() == "SHORT" or field[1].upper() == "LONG": 16 | arcpy.AddField_management(in_fc, field[0], field[1], field[2]) 17 | elif field[1].upper() == "STRING" or field[1].upper() == "TEXT": 18 | arcpy.AddField_management(in_fc, field[0], field[1], "", "", field[2]) 19 | elif field[1].upper() == "OID" or field[1].upper() == "GEOMETRY": 20 | pass 21 | else: 22 | arcpy.AddField_management(in_fc, field[0], field[1]) 23 | except arcpy.ExecuteError: 24 | arcpy.GetMessages() 25 | -------------------------------------------------------------------------------- /Batch_reprojection.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | 4 | import os 5 | import arcpy 6 | from arcpy import env 7 | 8 | # 允许覆盖地理处理操作 9 | env.overwriteOutput = False 10 | 11 | # 从外界获取的参数 12 | raster_path = arcpy.GetParameterAsText(0) 13 | out_coor_system = arcpy.GetParameterAsText(1) 14 | rs_type = arcpy.GetParameterAsText(2) 15 | c_size = arcpy.GetParameterAsText(3) 16 | d_dir_name = arcpy.GetParameterAsText(4) 17 | 18 | new_path_name = d_dir_name 19 | os.makedirs(raster_path + "\\"+ new_path_name) 20 | arcpy.AddMessage("Step1:Creating new folder named " + str(d_dir_name)) 21 | arcpy.AddMessage("Step1:Completed") 22 | 23 | 24 | def project_batch(): 25 | env.workspace = raster_path 26 | rafters = arcpy.ListRasters("*", "tif") 27 | for raster in rafters: 28 | out = "\\" + new_path_name + "\\" + "Pr_" + raster[:] 29 | arcpy.ProjectRaster_management(raster, out, out_coor_system, rs_type, c_size, "#", "#", "#") 30 | arcpy.AddMessage("Step2:Pr_"+raster[:]+"has done.") 31 | arcpy.SetProgressorPosition() 32 | arcpy.AddMessage("Step2:Completed") 33 | 34 | 35 | arcpy.ResetProgressor() 36 | if arcpy.CheckExtension("Spatial") == "Available": 37 | project_batch() 38 | else: 39 | arcpy.AddMessage("Error!!! Spatial Analyst is unavailable") 40 | -------------------------------------------------------------------------------- /07使用游标/TestCursor.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.CreateTable_management(os.getcwd(), "TestCursor.dbf") 4 | in_table = os.getcwd() + os.sep + "TestCursor.dbf" 5 | arcpy.AddField_management(in_table, "REMARKS", "TEXT", field_length=20) 6 | # Test InsertCursor 7 | cursor = arcpy.da.InsertCursor(in_table, "Field1") 8 | for i in range(1, 16): 9 | cursor.insertRow([i]) 10 | del cursor 11 | 12 | # Test SearchCursor 13 | field_addDelimiters = arcpy.AddFieldDelimiters(os.getcwd(), "Field1") 14 | sql_clause = field_addDelimiters + " < 7" 15 | print sql_clause 16 | sum_number = 0 17 | with arcpy.da.SearchCursor(in_table, "*", sql_clause) as cursor: 18 | for row in cursor: 19 | sum_number += row[1] 20 | print "The sum of 1 to 7 is " + str(sum_number) 21 | 22 | # Test UpdateCursor 23 | print sql_clause 24 | with arcpy.da.UpdateCursor(in_table, "*", sql_clause) as cursor: 25 | for row in cursor: 26 | print row[1] 27 | row[2] = str(row[1]) + " is smaller than 7" 28 | cursor.updateRow(row) 29 | 30 | sql_clause = field_addDelimiters + " > 7" 31 | print sql_clause 32 | with arcpy.da.UpdateCursor(in_table, ["Field1", "REMARKS"], sql_clause) as cursor: 33 | for row in cursor: 34 | print row[0] 35 | row[1] = str(row[1]) + " is bigger than 7" 36 | cursor.updateRow(row) 37 | -------------------------------------------------------------------------------- /01使用函数/07消息和错误处理/GetMessages.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.CreateFeatureclass_management(os.getcwd(), "testMessage.shp") 4 | fc = os.getcwd() + os.sep + "testMessage.shp" 5 | try: 6 | arcpy.AddField_management(fc, "TEST", "TEXT") 7 | arcpy.AddField_management(fc, "TEST", "TEXT") 8 | except arcpy.ExecuteError: 9 | pass 10 | print "Test GetMessageCount:" 11 | messageCount = arcpy.GetMessageCount() 12 | print messageCount 13 | print "Test GetMessages:" 14 | print arcpy.GetMessages() 15 | print "Test GetMessage:" 16 | print "GetMessage(0):",arcpy.GetMessage(0) 17 | print "GetMessage(1):",arcpy.GetMessage(1) 18 | print "GetMessage(2):",arcpy.GetMessage(2) 19 | print "Test GetIDMessage:" 20 | print "GetIDMessage(84001):",arcpy.GetIDMessage(84001) 21 | print "GetIDMessage(999999):",arcpy.GetIDMessage(999999) 22 | print "Test GetReturnCode:" 23 | print "Message[1]'s ReturnCode:", arcpy.GetReturnCode(1) 24 | print "Message[2]'s ReturnCode:", arcpy.GetReturnCode(2) 25 | print "Test GetSeverity:" 26 | print "Message[1]'s Severity:", arcpy.GetSeverity(1) 27 | print "Message[2]'s Severity:", arcpy.GetSeverity(2) 28 | print "Test GetSeverityLevel:" 29 | print arcpy.GetSeverityLevel() 30 | arcpy.SetSeverityLevel(1) 31 | print arcpy.GetSeverityLevel() 32 | print "Test GetMaxSeverity:" 33 | print arcpy.GetMaxSeverity() 34 | arcpy.Delete_management(fc) 35 | -------------------------------------------------------------------------------- /02使用类/TestCursor10.0.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | arcpy.CreateTable_management(os.getcwd(), "TestCursor.dbf") 4 | in_table = os.getcwd() + os.sep + "TestCursor.dbf" 5 | arcpy.AddField_management(in_table, "REMARKS", "TEXT", field_length=20) 6 | # Test InsertCursor 7 | rows = arcpy.InsertCursor(in_table) 8 | for i in range(1, 16): 9 | row = rows.newRow() 10 | row.setValue("Field1", i) 11 | rows.insertRow(row) 12 | del row 13 | del rows 14 | 15 | # Test SearchCursor 16 | field_addDelimiters = arcpy.AddFieldDelimiters(os.getcwd(), "Field1") 17 | sql_clause = field_addDelimiters + " < 7" 18 | print sql_clause 19 | sum_number = 0 20 | rows = arcpy.SearchCursor(in_table, sql_clause) 21 | for row in rows: 22 | sum_number += row.getValue("Field1") 23 | print "The sum of 1 to 7 is " + str(sum_number) 24 | del row 25 | del rows 26 | 27 | # Test UpdateCursor 28 | print sql_clause 29 | rows = arcpy.UpdateCursor(in_table, sql_clause) 30 | 31 | for row in rows: 32 | print row.getValue("Field1") 33 | row.setValue("REMARKS", str(row.getValue("Field1")) + " is smaller than 7") 34 | rows.updateRow(row) 35 | del row 36 | del rows 37 | 38 | sql_clause = field_addDelimiters + " > 7" 39 | print sql_clause 40 | rows = arcpy.UpdateCursor(in_table, sql_clause, ["Field1", "REMARKS"]) 41 | 42 | row = rows.next() 43 | while row: 44 | print row.getValue("Field1") 45 | row.setValue("REMARKS", str(row.getValue("Field1")) + " is bigger than 7") 46 | rows.updateRow(row) 47 | row = rows.next() 48 | del row 49 | del rows 50 | -------------------------------------------------------------------------------- /克里金插值和IDW插值/kriging.py: -------------------------------------------------------------------------------- 1 | import geopandas 2 | from math import radians, sin, cos, asin, sqrt 3 | import matplotlib.pyplot as plt 4 | import pandas as pd 5 | import numpy as np 6 | from mpl_toolkits.basemap import Basemap 7 | import fiona 8 | from pykrige import OrdinaryKriging 9 | from shapely.geometry import Polygon, Point 10 | 11 | 12 | 13 | 14 | workbook = pd.read_excel("pmdata.xlsx") 15 | lon,lat,pm = workbook['lon'],workbook['lat'],workbook['PM2.5'] 16 | 17 | #116.362 30.7578 121.9752 35.1245 18 | un_lon = np.linspace(116.362,121.9752,400) 19 | un_lat = np.linspace(30.7578,35.1245,400) 20 | 21 | 22 | OK = OrdinaryKriging(lon,lat,pm,variogram_model='gaussian',nlags=6) 23 | zgrid,ss = OK.execute('grid',un_lon,un_lat) 24 | 25 | xgrid,ygrid = np.meshgrid(un_lon,un_lat) 26 | 27 | 28 | 29 | 30 | 31 | shp = fiona.open('shp/江苏省_行政边界.shp') 32 | pol = shp.next() 33 | polygon = Polygon(pol['geometry']['coordinates'][0][0]) 34 | 35 | #np.nan 36 | for i in range(xgrid.shape[0]): 37 | for j in range(xgrid.shape[1]): 38 | plon = xgrid[i][j] 39 | plat = ygrid[i][j] 40 | if not polygon.contains(Point(plon,plat)): 41 | zgrid[i][j] = np.nan 42 | 43 | fig,ax = plt.subplots(figsize=(6,4.5),dpi=130,facecolor='white') 44 | 45 | base_map = Basemap( 46 | llcrnrlon=116.362, 47 | urcrnrlon=121.9752, 48 | llcrnrlat=30.7578, 49 | urcrnrlat=35.1245, 50 | lon_0=119, 51 | lat_0=33, 52 | ax=ax 53 | ) 54 | 55 | base_map.drawparallels(np.arange(30,36,1),labels=[1,0,0,0],fontsize=12,ax=ax) 56 | base_map.drawmeridians(np.arange(116,122,1),labels=[0,0,0,1],fontsize=12,ax=ax) 57 | 58 | base_map.readshapefile('shp/江苏省_行政边界','Js',True,default_encoding='ISO-8859-1') 59 | cp = base_map.pcolormesh(xgrid,ygrid,zgrid,cmap='Spectral_r',shading='auto') 60 | colorbar = base_map.colorbar(cp,label='克里金') 61 | base_map.contour(xgrid,ygrid,zgrid,colors='w') 62 | colorbar.outline.set_edgecolor('none') 63 | plt.axis('off') 64 | plt.show() -------------------------------------------------------------------------------- /01使用函数/06进度对话框/SetProgressor/SetProgressor.py: -------------------------------------------------------------------------------- 1 | import arcpy, time 2 | 3 | n = 5 4 | p = 1 5 | 6 | readTime = 1.5 # 停顿时间 7 | loopTime = 0.3 # 循环迭代延时 8 | 9 | # 首先显示的是默认的进度条显示形式 10 | # time sleep() 函数推迟调用线程的运行,可通过参数(指秒数),表示进程挂起的时间。 11 | arcpy.SetProgressor("default", "This is the default progressor") 12 | time.sleep(readTime) 13 | 14 | # 模拟显示执行多个任务时进度条及进度标签 15 | 16 | for i in xrange(1, 5): 17 | arcpy.SetProgressorLabel("Working on 'phase' {0}".format(i)) 18 | arcpy.AddMessage("Messages for phase {0}".format(i)) 19 | time.sleep(readTime) 20 | 21 | # 设置进度条为步进显示形式 22 | arcpy.SetProgressor("step", 23 | "Step progressor: Counting from 0 to {0}".format(n), 24 | 0, n, p) 25 | time.sleep(readTime) 26 | 27 | # 通过循环模拟进度条步进显示 28 | 29 | for i in range(n): 30 | if (i % p) == 0: 31 | arcpy.SetProgressorLabel("Iteration: {0}".format(i)) 32 | arcpy.SetProgressorPosition(i) 33 | time.sleep(loopTime) 34 | 35 | # 更新进度显示的最后部分(上面的range只是到4,进度不能到100%) 36 | # 37 | arcpy.SetProgressorLabel("Iteration: {0}".format(i + 1)) 38 | arcpy.SetProgressorPosition(i + 1) 39 | # 信息框中添加进度向上显示完成消息 40 | # 41 | arcpy.AddMessage("Done counting up\n") 42 | time.sleep(readTime) 43 | 44 | # 只是为了有趣,让进度条再倒回去 45 | # 46 | arcpy.SetProgressor("default", "Default progressor: Now we'll do a countdown") 47 | time.sleep(readTime) 48 | arcpy.AddMessage("Here comes the countdown...") 49 | arcpy.SetProgressor("step", 50 | "Step progressor: Counting backwards from {0}".format(n), 51 | 0, n, p) 52 | time.sleep(readTime) 53 | arcpy.AddMessage("Counting down now...\n") 54 | 55 | for i in range(n, 0, -1): 56 | if (i % p) == 0: 57 | arcpy.SetProgressorLabel("Iteration: {0}".format(i)) 58 | arcpy.SetProgressorPosition(i) 59 | time.sleep(loopTime) 60 | 61 | # 更新剩余进度显示 62 | arcpy.SetProgressorLabel("Iteration: {0}".format(0)) 63 | arcpy.SetProgressorPosition(0) 64 | time.sleep(readTime) 65 | arcpy.AddMessage("All done") 66 | arcpy.ResetProgressor() 67 | -------------------------------------------------------------------------------- /克里金插值和IDW插值/idw.py: -------------------------------------------------------------------------------- 1 | import geopandas 2 | from math import radians, sin, cos, asin, sqrt 3 | import matplotlib.pyplot as plt 4 | import pandas as pd 5 | import numpy as np 6 | from mpl_toolkits.basemap import Basemap 7 | import fiona 8 | from shapely.geometry import Polygon, Point 9 | 10 | 11 | def caldis(lon1, lat1, lon2, lat2): 12 | a = radians(lat1-lat2) 13 | b = radians(lon1-lon2) 14 | lat1,lat2 = radians(lat1),radians(lat2) 15 | t = sin(a/2)**2 + cos(lat1)*cos(lat2)*sin(b/2)**2 16 | d = 2*asin(sqrt(t))*6378.137 17 | return d 18 | 19 | def idw(lon, lat, pm, x, y): 20 | lstz = [] 21 | for i in range(len(x)): 22 | lstd = [] 23 | for j in range(len(lon)): 24 | d = caldis(lon[j],lat[j],x[i],y[i]) 25 | lstd.append(d) 26 | sqdis = list(1/np.power(lstd,2)) 27 | sumdis = np.sum(sqdis) 28 | 29 | z = np.sum(np.array(pm)*np.array(sqdis))/sumdis 30 | lstz.append(z) 31 | return lstz 32 | 33 | workbook = pd.read_excel("pmdata.xlsx") 34 | lon,lat,pm = workbook['lon'],workbook['lat'],workbook['PM2.5'] 35 | 36 | #116.362 30.7578 121.9752 35.1245 37 | un_lon = np.linspace(116.362,121.9752,400) 38 | un_lat = np.linspace(30.7578,35.1245,400) 39 | 40 | xgrid,ygrid = np.meshgrid(un_lon,un_lat) 41 | 42 | x ,y = xgrid.flatten(),ygrid.flatten() 43 | 44 | lstz = idw(lon,lat,pm,x,y) 45 | 46 | zgrid = np.array(lstz).reshape(xgrid.shape) 47 | 48 | shp = fiona.open('shp/江苏省_行政边界.shp') 49 | pol = shp.next() 50 | polygon = Polygon(pol['geometry']['coordinates'][0][0]) 51 | 52 | #np.nan 53 | for i in range(xgrid.shape[0]): 54 | for j in range(xgrid.shape[1]): 55 | plon = xgrid[i][j] 56 | plat = ygrid[i][j] 57 | if not polygon.contains(Point(plon,plat)): 58 | zgrid[i][j] = np.nan 59 | 60 | fig,ax = plt.subplots(figsize=(6,4.5),dpi=130,facecolor='white') 61 | 62 | base_map = Basemap( 63 | llcrnrlon=116.362, 64 | urcrnrlon=121.9752, 65 | llcrnrlat=30.7578, 66 | urcrnrlat=35.1245, 67 | lon_0=119, 68 | lat_0=33, 69 | ax=ax 70 | ) 71 | 72 | base_map.drawparallels(np.arange(30,36,1),labels=[1,0,0,0],fontsize=12,ax=ax) 73 | base_map.drawmeridians(np.arange(116,122,1),labels=[0,0,0,1],fontsize=12,ax=ax) 74 | 75 | base_map.readshapefile('shp/江苏省_行政边界','Js',True,default_encoding='ISO-8859-1') 76 | cp = base_map.pcolormesh(xgrid,ygrid,zgrid,cmap='Spectral_r',shading='auto') 77 | colorbar = base_map.colorbar(cp,label='IDW') 78 | base_map.contour(xgrid,ygrid,zgrid,colors='w') 79 | colorbar.outline.set_edgecolor('none') 80 | plt.axis('off') 81 | plt.show() -------------------------------------------------------------------------------- /克里金插值和IDW插值/RBF插值.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # author:dongyi 4 | # datetime: 2021/1/16 20:28 5 | # ide: PyCharm 6 | # env:python3.8 7 | import numpy as np 8 | import cartopy.crs as ccrs 9 | import cartopy.feature as cfeat 10 | from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER 11 | from cartopy.io.shapereader import Reader 12 | import matplotlib.pyplot as plt 13 | import matplotlib.ticker as mticker 14 | from scipy.interpolate import Rbf#引入径向基函数 15 | import pandas as pd 16 | import maskout2 17 | from cartopy.mpl.ticker import LongitudeFormatter,LatitudeFormatter 18 | from matplotlib import rcParams 19 | config={"font.family":'Times New Roman',"font.size":16,"mathtext.fontset":'stix'} 20 | rcParams.update(config) 21 | plt.rcParams['figure.figsize']=(12,10) 22 | shp_path=r'F:/Rpython/lp17/data/xinjiang0819.shp' 23 | proj= ccrs.PlateCarree() # 简写投影 24 | filename=r'F:/Rpython/lp28/data/XJ1224.xlsx' 25 | df=pd.read_excel(filename)#读取文件 26 | lon=df['lon']#读取站点经度 27 | lat=df['lat']#读取站点纬度 28 | tem=df['h']#读取站点气温 29 | # 创建画布 30 | fig = plt.figure(figsize=(12,10),dpi=600) 31 | olon=np.linspace(70,100,90) 32 | olat=np.linspace(30,55,75) 33 | olon,olat=np.meshgrid(olon,olat)#网格化 34 | func=Rbf(lon,lat,tem,function='cubic')#定义径向基函数插值 35 | tem_new=func(olon,olat)#获得插值后的网格气温 36 | ax = fig.subplots(1, 1, subplot_kw={'projection': proj}) # 创建子图 37 | extent=[73,97,34,50]#限定绘图范围 38 | reader = Reader(shp_path) 39 | enshicity = cfeat.ShapelyFeature(reader.geometries(), proj, edgecolor='k', facecolor='none') 40 | ax.add_feature(enshicity, linewidth=0.7)#添加市界细节 41 | ax.set_extent(extent,crs=proj) 42 | ax.set_xticks(np.arange(extent[0],extent[1]+1,3),crs=proj) 43 | ax.set_yticks(np.arange(extent[-2],extent[-1]+1,2),crs=proj) 44 | ax.xaxis.set_major_formatter(LongitudeFormatter()) 45 | ax.yaxis.set_major_formatter(LatitudeFormatter()) 46 | cs1= ax.contourf(olon,olat,tem_new,levels=np.arange(0,2000,200),cmap='gist_rainbow',extend='both')#画图cmap='Spectral_r', 47 | cs2= ax.contour(olon,olat,tem_new,colors='red',linewidths=0.6)#画图 48 | b=plt.colorbar(cs1,shrink=0.65,orientation='vertical',extend='both',pad=0.035,aspect=20) #orientation='horizontal' 49 | clip1=maskout2.shp2clip(cs1,ax,r'F:/Rpython/lp17/data/xinjiang0819.shp') #白化1 50 | clip2=maskout2.shp2clip(cs2,ax,r'F:/Rpython/lp17/data/xinjiang0819.shp') #白化2 51 | font3={'family':'SimHei','size':8,'color':'k'} 52 | plt.scatter(df['lon'].values,df['lat'].values,marker='o',s=6,color ="k") 53 | for i, j, k in list(zip(df['lon'].values, df['lat'].values, df['name'].values)): 54 | plt.text(i-0.2,j-0.3,k,fontdict=font3) 55 | plt.savefig('F:/Rpython/lp28/plot7.2.png',dpi=600) 56 | plt.show() -------------------------------------------------------------------------------- /Batch_rename_tif.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import re 3 | import os 4 | import sys 5 | import arcpy 6 | 7 | reload(sys) 8 | sys.setdefaultencoding('utf-8') 9 | 10 | 11 | def num_cvt_day_and_month(year, num): 12 | # 输入年份year和第num天返回该天对应的月和日 13 | t_0 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 14 | t_1 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 15 | if year % 4 != 0: 16 | t = t_0[:] 17 | else: 18 | t = t_1[:] 19 | month_r = 1 20 | day_r = 1 21 | while True: 22 | if num - sum(t[:month_r]) <= 0: 23 | day_r = num - sum(t[:month_r - 1]) 24 | month_r = month_r 25 | break 26 | else: 27 | month_r += 1 28 | continue 29 | return day_r, month_r 30 | 31 | 32 | class RenameModisFile: 33 | def __init__(self, file_name): 34 | self.file_name = file_name 35 | 36 | def breakup_file_name(self): 37 | parts = self.file_name.split('.') 38 | # a = parts[0] # MOD13A3 39 | b = parts[1] # A2000032 40 | c = parts[2] # h26v05 41 | d = parts[-2] # 1_km_monthly_NDVI 42 | e = parts[-1] # .hdf or .tif 43 | return b, c, d, e 44 | 45 | def split_year_and_num(self, str_time): 46 | if re.match(r'A\d{4}[0-9][0-9][0-9]', str_time): 47 | return str_time[1:5], str_time[-3:] 48 | else: 49 | arcpy.AddMessage("请检查文件名格式是否正确") 50 | raise IndexError 51 | 52 | def cvt_new_form(self): 53 | data_time, data_position, others, suffix = self.breakup_file_name() 54 | in_year, in_num = self.split_year_and_num(data_time) 55 | out_day, out_month = num_cvt_day_and_month(int(in_year), int(in_num)) 56 | new_form = 'A%sM%02dD%02d_%s_%s.%s' % (in_year, out_month, out_day, data_position, others, suffix) 57 | return new_form 58 | 59 | 60 | in_rasters = arcpy.GetParameterAsText(0) 61 | """ 62 | file_pahts:由全部栅格完整路径组成的列表 63 | file_dirs:由栅格文件所在目录组成的列表 64 | full_neams:由栅格名字组成的列表 65 | """ 66 | file_paths = in_rasters.split(';') # type:list 67 | file_dirs = [] 68 | full_names = [] 69 | for file_path in file_paths: 70 | file_dir, full_name = os.path.split(file_path) 71 | file_dirs.append(file_dir) 72 | full_names.append(full_name) 73 | old_names = full_names 74 | 75 | """ 76 | old_names:待进行重命名的栅格文件名组成的列表 77 | new_names:重命名后的栅格文件名组成的列表 78 | """ 79 | new_names = [] 80 | for old_name in old_names: 81 | rename = RenameModisFile(old_name) 82 | new_name = rename.cvt_new_form() 83 | new_names.append(new_name) 84 | for i in range(len(new_names)): 85 | os.rename(file_dirs[i] + '\\' + old_names[i], file_dirs[i] + '\\' + new_names[i]) 86 | --------------------------------------------------------------------------------