【问题标题】:How to convert two coordinate columns to a column of Shapely points如何将两个坐标列转换为一列 Shapely 点
【发布时间】:2020-04-12 20:21:48
【问题描述】:

我正在尝试对整个列执行操作,但出现类型错误,我想创建一个包含 Shapely Point 的列:

crime_df = crime_df[crime_df['Latitude'].notna()]
crime_df = crime_df[crime_df['Longitude'].notna()]

crime_df['Longitude'] = crime_df['Longitude'].astype(float)
crime_df['Latitude'] = crime_df['Latitude'].astype(float)

print (crime_df['Longitude'])
print (crime_df['Latitude'])

crime_df['point'] = Point(crime_df['Longitude'], crime_df['Latitude'])

输出:

18626    -87.647379
Name: Longitude, Length: 222, dtype: float64

18626    41.781100
Name: Latitude, Length: 222, dtype: float64

TypeError: cannot convert the series to <class 'float'>

【问题讨论】:

    标签: python pandas point shapely


    【解决方案1】:

    我认为您需要分别处理每个点,因此需要 DataFrame.apply 和 lambda 函数:

    crime_df['point'] = crime_df.apply(lambda x: Point(x['Longitude'], x['Latitude'], axis=1)
    

    或者感谢@N。沃达:

    crime_df["point"] = crime_df[["Longitude", "Latitude"]].apply(Point, axis=1)
    

    或者列表理解替代方案是:

    crime_df['point'] = [Point(lon, lat) 
                                     for lon, lat in crime_df[['Longitude','Latitude']].values]
    

    编辑:我认为对于矢量化方式可以使用geopandas.points_from_xy,例如:

    gdf = geopandas.GeoDataFrame(df,geometry=geopandas.points_from_xy(df.Longitude,df.Latitude))
    

    【讨论】:

    • 啊 - 我试图对过程进行矢量化以加快速度,在这种情况下不可能吗?
    • 这可以做得更干净一点,如下所示:crime_df["point"] = crime_df[["Longitude", "Latitude"]].apply(Point, axis=1),因为 __init__ 已经可以调用,并且 Shapely Point understands sequences :)。
    • @TomSelleck - 我认为问题是Point 不可能以这种方式创建。我找到了另一种方式,编辑了答案。
    • IIUC,如果安装了 PyGEOS,最后一个选项应该会更快。否则,它只是一个简单的列表理解。请参阅 source codenote on the optional PyGEOS dependency in the docs
    猜你喜欢
    • 2021-09-02
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2014-08-16
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多