Python 3.x 从数据帧中的一个或多个字符串值创建列表

Python 3.x 从数据帧中的一个或多个字符串值创建列表,python-3.x,string,pandas,list,geopandas,Python 3.x,String,Pandas,List,Geopandas,我有一个数据帧,它是由两个Geopandas.GeoDataFrame对象之间的空间连接产生的 由于有多个项目与目标要素重叠,因此行已被复制,因此每一行都具有来自每个重叠实体的继承信息。为了模拟这种情况,我们可以运行以下行: world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) cities = geopandas.read_file(geopandas.datasets.get_path(

我有一个数据帧,它是由两个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')
我试图在world geodaframe中生成一个新列,该列包含长度为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\u countries[“City”].tolist()上。我得到的错误是
“str”对象没有属性“tolist”

根据我的测试和调查,我似乎得到了这个错误,因为第一个国家[
countries\u with_city.loc[countries\u with_city.index==world.loc[1,“name”]
]内部只有一个城市。因此,当我对数据帧进行切片时,只有一行的index=1会使结果成为字符串,而不是可以列出的数据帧

有没有一种简单的方法可以让代码在任何情况下都能正常工作?(当有0、1和多个城市时)。目标是生成城市名称列表,然后将其写入世界数据框架


我正在使用python 3

如果我理解正确,一种方法是构建从国家名称到城市名称列表的映射:

# Build a Series with index=countries, values=cities
country2city = countries_with_city.groupby('name')['City'].agg(lambda x: list(x))

# Use the mapping on the name column of the world DataFrame
world['city_list'] = world['name'].map(county)

# Peek at a nontrivial part of the result
world.drop('geometry', axis=1).tail()
        pop_est continent          name iso_a3  gdp_md_est                                          city_list
172    218519.0   Oceania       Vanuatu    VUT       988.5                                                NaN
173  23822783.0      Asia         Yemen    YEM     55280.0                                            [Sanaa]
174  49052489.0    Africa  South Africa    ZAF    491000.0  [Cape Town, Bloemfontein, Johannesburg, Pretoria]
175  11862740.0    Africa        Zambia    ZMB     17500.0                                           [Lusaka]
176  12619600.0    Africa      Zimbabwe    ZWE      9323.0                                           [Harare]
如果要立即打印城市列表,可以将每个列表中的字符串连接起来以删除方括号:

world['city_str'] = world['city_list'].apply(lambda x: ', '.join(c for c in x)
                                             if x is not np.nan else None)

# Sanity-check result
world.filter(like='city').tail()
                                             city_list                                         city_str
172                                                NaN                                             None
173                                            [Sanaa]                                            Sanaa
174  [Cape Town, Bloemfontein, Johannesburg, Pretoria]  Cape Town, Bloemfontein, Johannesburg, Pretoria
175                                           [Lusaka]                                           Lusaka
176                                           [Harare]                                           Harare