从熊猫数据框中的一个或多个字符串值中列出

时间:2019-02-16 01:01:58

标签: 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('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

1 个答案:

答案 0 :(得分:1)

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

# 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