🖥️ IT, 컴퓨터/🐍 Python

[Python] Geopandas로 폴리곤의 중심점(centroid) 계산하기

김 홍시 2025. 4. 14.
반응형

Python에서 .shp (Shapefile) 파일의 폴리곤 중심점(centroid)을 계산하려면 일반적으로 geopandas 라이브러리를 사용합니다. 아래는 전체적인 절차입니다.


✅ 1. 필요 라이브러리 설치 (처음 한 번만)

pip install geopandas

✅ 2. 코드 예시: 폴리곤의 센트로이드 구하기

import geopandas as gpd

# SHP 파일 불러오기
gdf = gpd.read_file("your_file.shp")  # 파일 경로를 적어주세요

# 센트로이드 계산
gdf['centroid'] = gdf.geometry.centroid

# 결과 확인
print(gdf[['geometry', 'centroid']].head())

# 필요하다면 centroid를 새로운 shp 파일로 저장할 수도 있습니다.
gdf_centroids = gdf.copy()
gdf_centroids.set_geometry('centroid', inplace=True)
gdf_centroids.to_file("centroids.shp")

⚠️ 주의사항

  • centroid는 폴리곤의 기하학적 중심이며, 꼭 폴리곤 내부에 위치하지 않을 수도 있습니다.
    → 만약 항상 폴리곤 내부에 있는 중심이 필요하다면 representative_point()를 사용하세요:
    gdf['rep_point'] = gdf.geometry.representative_point()

필요에 따라 centroidx, y 좌표로 나눠서 사용하고 싶다면 아래와 같이 확장할 수 있습니다:

gdf['centroid_x'] = gdf.centroid.x
gdf['centroid_y'] = gdf.centroid.y
반응형

댓글