使用游标将excel不同表的列关联,并根据两表间相同的列值逐行更新数据

测试为:sheet2$,sheet3$两张表都有name字段,根据name字段值相等,将sheet3$中的coltest列添加到sheet2$中的coltest列,测试语句如下:

Declare @coltest nvarchar(255)
Declare @name nvarchar(255)
Declare MyCursor Cursor Scroll
For select coltest,name from openrowset('microsoft.jet.oledb.4.0','excel 5.0;hdr=yes;database=D:/My Documents/test.xls;',sheet3$)
open MyCursor
Fetch next From MyCursor
Into @coltest,@name
While(@@Fetch_Status = 0)
 Begin
   Begin
   update openrowset('microsoft.jet.oledb.4.0','excel 5.0;hdr=yes;database=D:/My Documents/test.xls;',sheet2$)
   set coltest=@coltest
   where name=@name            
   End
 Fetch next From MyCursor
 Into @coltest,@name
 End
Close MyCursor
Deallocate MyCursor

import arcpy # ArcGIS的Python模块,用于地理数据处理 import numpy as np # 数计算库,处理数组 import pandas as pd # 数据处理库,类似Excel格 from sklearn.svm import SVC # 支持向量机分类模型 from sklearn.preprocessing import StandardScaler # 数据标准化工具 # 设置工作空(您的数据存放位置) arcpy.env.workspace = r"E:\py_train\20250615\luoyang\svm\1" # 修改为您的实际文件夹路径 arcpy.env.overwriteOutput = True # 允许覆盖已有文件 # 输入数据 sample_points = "dzd_0_1.shp" # 您已经准备好的点文件(200灾害点+400非灾害点) # 定义点文件中的字段名(您需要根据实际情况修改) factor_fields = ["dist", "podu", "zdmd", "3cd", "lizhi", "2ld", "nianxing", "curva", "ndvi","shuixi","jiangyu"] label_field = "leixing" # 这个字段标记点是灾害点(1)还是非灾害点(0) # 从点文件中读取数据 print("从点文件读取已提取的因子...") fields = factor_fields + [label_field] # 需要读取的所有字段 data_dict = {field: [] for field in fields} # 创建空字典存储数据 # 使用游标读取所有属性(类似打开Excel格读取数据) with arcpy.da.SearchCursor(sample_points, fields) as cursor: for row in cursor: for i, field in enumerate(fields): data_dict[field].append(row[i]) # 逐行读取数据 # 转换为DataFrame(类似Excel格) df = pd.DataFrame(data_dict) print(f"成功读取 {len(df)} 个样本点数据") # 分离特征(X)和标签(y) X = df[factor_fields] # 所有因子(坡度、坡向等) y = df[label_field] # 灾害类型(0或1) # 清理无效(删除空数据) df_clean = df.dropna() if len(df) != len(df_clean): print(f"移除 {len(df) - len(df_clean)} 个包含空的样本") X = df_clean[factor_fields] # 清理后的因子 y = df_clean[label_field] # 清理后的标签 # 数据标准化(非常重要!) print("标准化数据...") scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 转换为标准格式 print("训练SVM模型...") # 创建支持向量机分类器 svm_model = SVC( kernel='rbf', # 使用径向基函数(最常用) C=1.0, # 正则化参数(默认) gamma='scale', # 核函数系数(自动计算) probability=True # 输出概率(0-1之) ) # 使用全部数据训练模型 svm_model.fit(X_scaled, y) print("SVM模型训练完成") # 读取所有栅格数据 raster_arrays = {} print("读取栅格数据...") for name in factor_fields: # 遍历所有因子 path = f"{name}.tif" # 假设栅格文件名与字段名相同 print(f" - {path}") # 使用arcpy.RasterToNumPyArray而不是从sa导入 raster_arrays[name] = arcpy.RasterToNumPyArray(path) # 转换为数组 # 获取参考栅格信息(用于结果输出) ref_raster = f"{factor_fields[0]}.tif" # 第一个栅格 desc = arcpy.Describe(ref_raster) cell_size = desc.meanCellWidth # 像元大小(30米) extent = desc.extent # 范围 spatial_ref = desc.spatialReference # 坐标系 # 创建全区预测网格 rows, cols = raster_arrays[factor_fields[0]].shape prediction = np.zeros((rows, cols), dtype=np.float32) # 分块处理(避免内存不足) block_size = 1000 # 每次处理1000行 print(f"开始全区预测,总行数: {rows},块大小: {block_size}行") for i in range(0, rows, block_size): i_end = min(i + block_size, rows) print(f"处理行 {i} 到 {i_end-1} ({i_end-i}行)") # 提取当前块的所有因子 block_data = {} for name in factor_fields: block_data[name] = raster_arrays[name][i:i_end, :].flatten() # 创建数据框 block_df = pd.DataFrame(block_data) # 标准化(使用与训练数据相同的缩放器) block_scaled = scaler.transform(block_df) # 预测灾害发生概率 proba = svm_model.predict_proba(block_scaled)[:, 1] prediction[i:i_end, :] = proba.reshape((i_end - i), cols) print("生成易发性栅格...") # 将预测数组转为栅格 # 使用arcpy.NumPyArrayToRaster而不是从sa导入 susceptibility_raster = arcpy.NumPyArrayToRaster( prediction, # 预测结果数组 arcpy.Point(extent.XMin, extent.YMin), # 左上角坐标 cell_size, cell_size # 像元大小 ) # 设置坐标系 arcpy.management.DefineProjection( in_dataset=susceptibility_raster, coor_system=spatial_ref ) # 保存结果 output_raster = "Geohazard_Susceptibility.tif" susceptibility_raster.save(output_raster) print(f"易发性栅格已保存至: {output_raster}") print("处理完成! ") 以上代码在arcgis pro 2.8 notebook中提示ValueError Traceback (most recent call last) In [1]: Line 97: block_df = pd.DataFrame(block_data) File C:\Users\Administrator\AppData\Local\ESRI\conda\envs\arcgispro-py3-clone\lib\site-packages\pandas\core\frame.py, in __init__: Line 529: mgr = init_dict(data, index, columns, dtype=dtype) File C:\Users\Administrator\AppData\Local\ESRI\conda\envs\arcgispro-py3-clone\lib\site-packages\pandas\core\internals\construction.py, in init_dict: Line 287: return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype) File C:\Users\Administrator\AppData\Local\ESRI\conda\envs\arcgispro-py3-clone\lib\site-packages\pandas\core\internals\construction.py, in arrays_to_mgr: Line 80: index = extract_index(arrays) File C:\Users\Administrator\AppData\Local\ESRI\conda\envs\arcgispro-py3-clone\lib\site-packages\pandas\core\internals\construction.py, in extract_index: Line 401: raise ValueError("arrays must all be same length") ValueError: arrays must all be same length
最新发布
06-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值