使用GeoSeries绘制城市Shapefile中K-Means聚类结果时出现TypeError错误
TypeError When Creating a GeoSeries of Cluster Centers Let's break down what's causing your error and how to fix it:
The Root Cause
Your line:
centers_gseries = GeoSeries(map(Point, zip(centers[:,1], centers[:,0])))
is failing because map passes each item from zip() as a single tuple argument to Point(), but the Point constructor expects two separate positional arguments: x and y. When map feeds a tuple like (lat, lon) to Point, it's only passing one argument, hence the "missing 1 required positional argument: 'y'" error.
Solutions
You have a couple of straightforward fixes:
1. Use a List Comprehension (Most Readable)
Unpack the coordinate tuples explicitly when creating Point objects:
from shapely.geometry import Point import geopandas as gpd # ... your existing code ... centers_gseries = gpd.GeoSeries([Point(x, y) for x, y in zip(centers[:,1], centers[:,0])]) centers_gseries.plot(ax=ax, alpha=1, marker='X', color='red', markersize=100, zorder=3)
2. Use lambda to Unpack Tuples
If you prefer to stick with map, use a lambda function to unpack each coordinate tuple:
centers_gseries = gpd.GeoSeries(map(lambda coord: Point(*coord), zip(centers[:,1], centers[:,0])))
Bonus: Verify Coordinate Order
Double-check that centers[:,1] is your longitude (x) and centers[:,0] is your latitude (y) — GeoPandas uses (x, y) which corresponds to (longitude, latitude) for most coordinate systems. If you have them reversed, your cluster centers will be plotted in the wrong location!
Modified Full Code Snippet
Here's how your updated clustering and plotting code would look:
from shapely.geometry import Point import geopandas as gpd from sklearn.cluster import MiniBatchKMeans # ... your data preparation code ... ssd = [] for i in range(1, 10): # Example cluster range km = MiniBatchKMeans(n_clusters=i) km.fit_predict(df_pickup) ssd.append(km.inertia_) df_pickup['cluster'] = km.labels_ # Create GeoDataFrame for pickup points geo_df = gpd.GeoDataFrame( df_pickup.drop(['longitud','latitud'], axis=1), geometry=gpd.points_from_xy(x=df_pickup.longitud, y=df_pickup.latitud) ) # Fix cluster centers GeoSeries creation centers = km.cluster_centers_ centers_gseries = gpd.GeoSeries([Point(x, y) for x, y in zip(centers[:,1], centers[:,0])]) # Plot centers_gseries.plot(ax=ax, alpha=1, marker='X', color='red', markersize=100, zorder=3)
内容的提问来源于stack exchange,提问作者PaulCoder

