python-3.x - 从 Pandas 数据框中的一个或多个字符串值创建一个列表

标签 python-3.x string pandas list geopandas

我有一个数据框,它是由 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

最佳答案

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

# 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

关于python-3.x - 从 Pandas 数据框中的一个或多个字符串值创建一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54718875/

相关文章:

python-3.x - 在 tensorflow 数据集上应用 map 执行速度非常慢

python - 使用 type() 手动创建新类时,子类 __module__ 设置为元类模块

python - 拆分数字和单词 pandas 保留索引

python pandas重命名数据框

python - 如何根据查找数据框检查由字符串列表组成的数据框并执行计算?

python - 使用 Python Pandas 使用每日数据的月平均值

python-3.x - 我可以在 python3 中格式化文档字符串吗

python-3.x - 如何减少深度强化学习算法的内存使用?

c# - 获取两个字符串的公共(public)前缀

java - 如何在 Java 中删除从 '<' 到 '>' 的整个子串