基于arcpy实现空间数据聚类,kmeans
并不能直接进行空间数据的聚类,原理是读取要素的x,y坐标来进行聚类,然后将聚类中心保存为空间数据以达到效果
# encoding: utf-8
from sklearn.cluster import KMeans
import numpy as np
import arcpy
import pandas as pd
from arcpy import env
env.workspace=r"D:\84.gdb"
target="bujiandian"
cursor=arcpy.SearchCursor(target)
allfea=[]
dic={}
name="ysdm"#代码要素列别的字段
for row in cursor :
ls=[]
if(dic.has_key(row.getValue(name))):
dic[row.getValue(name)]+=1
else:
dic[row.getValue(name)] = 1
ls.append(row.getValue(name))
ls.append(row.getValue("ptx"))
ls.append(row.getValue("pty"))
allfea.append(ls)
data2=pd.DataFrame(allfea,columns=[name,"ptx","pty"])
dataFilter=data2.query(name+"=='9000402'")
#取坐标进行聚类
df1 = dataFilter.ix[:,1 :]
kmeans = KMeans(n_clusters=3, random_state=10).fit(df1)
#dfl是聚类的结果
df1['jllable'] = kmeans.labels_
df_count_type = df1.groupby('jllable').apply(np.size)
##聚类中心
cent=kmeans.cluster_centers_
#将聚类中心保存为空间数据
sr = arcpy.SpatialReference(4326)
fc=arcpy.CreateFeatureclass_management( r"D:\cs","test.shp", "POINT", "", "","", sr)
arcpy.AddField_management(r"D:\cs\test.shp", "leibie", "TEXT")
cursor=arcpy.InsertCursor(fc)
for line in cent:
feature = cursor.newRow()
# Add the point geometry to the feature
vertex = arcpy.CreateObject("Point")
vertex.X = line[0]
vertex.Y =line[1]
feature.shape = vertex
# Add attributes
feature.leibie = "shumu"
# write to shapefile
cursor.insertRow(feature)
del cursor
del fc
转载自:https://blog.csdn.net/A873054267/article/details/84305281


