【问题标题】:Make a list from one OR many string values in a pandas dataframe从 pandas 数据框中的一个或多个字符串值创建一个列表
【发布时间】: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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 2017-04-30
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      相关资源
      最近更新 更多