【发布时间】:2019-07-10 03:51:10
【问题描述】:
我有一个数据框,它是由 2 个 Geopandas.GeoDataFrame 对象之间的空间连接产生的。
因为有多个项目与目标要素重叠,所以行已被复制,因此每一行都具有来自每个重叠实体的继承信息。为了模拟这种情况,我们可以运行以下几行:
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
cities = cities[['geometry', 'name']]
cities = cities.rename(columns={'name':'City'})
countries_with_city = geopandas.sjoin(world, cities, how="inner", op='intersects')
我正在尝试在世界地理框架中生成一个新列,其中包含长度为 0,1 或 +1 的列表,每个国家/地区的所有重叠城市的 "City" 属性。为此,我到目前为止写了这个:
for country in world.index:
subset_countries = countries_with_city.loc[countries_with_city.index==world.loc[country, "name"]]
a = subset_countries["City"].tolist()
list_of_names = list(subset_countries["City"])
world[list_of_names]=list_of_names
但是,当我运行此代码时,我卡在a = subset_countries["City"].tolist() 行。我得到的错误是'str' object has no attribute 'tolist'。
根据我的测试和调查,我似乎收到了这个错误,因为第一个国家 [countries_with_city.loc[countries_with_city.index==world.loc[1, "name"]]] 里面只有一个城市。因此,当我对数据框进行切片时,事实上只有一行 index=1 使结果成为字符串,而不是可以列出的数据框。
有没有一种简单的方法可以让代码在任何情况下都能正常工作? (当有 0、1 和许多城市时)。目标是生成一个城市名称列表,然后将其写入世界数据框中。
我正在研究 python 3
【问题讨论】:
标签: python-3.x string pandas list geopandas