Pythonでcsvファイルをshpに変換
https://blog.csdn.net/qq_23926575/article/details/82316965から転載Xuedixinには、CSV形式のファイルをシェープファイル形式に変換し、それを表示および分析のためにArcMapにロードするという要件がよくあります。ArcMap自体には、次のような機能があります。
ファイル->データの追加-> XYデータの追加:ファイルパスを選択し、Xフィールド(経度)とYフィールド(緯度)を指定します。デフォルトの座標系はWGS84座標系です。
このarcMapの機能は非常に便利ですが、データ量が多いため、100万個近くのデータがあり、コードによるフォーマット変換の効率が高くなります。
次のコードは次のリンクを参照しています:pyshpを使用して.csvファイルを.shpに変換しますか?
pyshpモジュール、csvモジュール、コーデックモジュールを使用する必要があり、pip installをインストールできます。
以下のコードを貼り付けます。
現在、変換できるのはポイントタイプのデータのみです。
#-*-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 | バツ | y |
---|---|---|---|
1 | ハリヤーナ州、ハリヤーナ州、インド | 76.9806 | 29.6161 |
2 | ムンバイ、マハラシュトラ州、インド | 72.8258 | 18.975 |
その結果