python——csv文件轉換爲shp
轉載自https://blog.csdn.net/qq_23926575/article/details/82316965學地信的經常會有這樣的需求,即將csv格式的文件轉換爲shapefile格式加載到arcMap中進行顯示與分析,arcMap本身提供了這樣的功能,即
文件->添加數據->添加XY數據:選擇文件路徑,指定X字段(longitude)、Y字段(latitude)即可,默認座標系爲WGS84座標系。
arcMap的這個功能非常方便,但因爲我的數據量較大,有接近100萬條數據,故通過代碼進行格式轉換效率更高點。
下面的代碼參考如下鏈接:Using pyshp to convert .csv file to .shp?
需要用到pyshp模塊、csv模塊、codecs模塊,pip install 安裝即可。
下面貼上代碼:
目前只能轉換point類型數據
#-*-coding:utf-8-*-
import shapefile as shp
import csv
import codecs
import os
def trans_point(folder, fn, idlng, idlat, delimiter=','):
# create a point shapefile
output_shp = shp.Writer(shp.POINT)
# for every record there must be a corresponding geometry.
output_shp.autoBalance = 1
# create the field names and data type for each.you can omit fields here
# output_shp.field('id','N') # number
output_shp.field('longitude', 'F', 10, 8) # float
output_shp.field('latitude', 'F', 10, 8) # float
output_shp.field('locname','C',100) # string, max-length
# access the CSV file
with codecs.open(folder + fn, 'rb', 'utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=delimiter)
# skip the header
next(reader, None)
#loop through each of the rows and assign the attributes to variables
for row in reader:
# idx = row[0]
locname= row[1]
lng= float(row[idlng])
lat = float(row[idlat])
print lng, lat
# create the point geometry
output_shp.point(lng, lat)
# add attribute data
output_shp.record(lng, lat, locname)
output_shp.save(folder + "%s.shp"%fn.split('.')[0]) # save the Shapefile
if __name__ == '__main__':
folder = 'C:\Users\MaMQ\Desktop' + os.sep
fn = 'test.csv'
trans_point(folder, fn, 2, 3)
示例數據
id | locname | x | y |
---|---|---|---|
1 | Haryana, Haryana, India | 76.9806 | 29.6161 |
2 | Mumbai, Maharashtra, India | 72.8258 | 18.975 |
結果