You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从XML数据构建含指定4列的Pandas DataFrame?

问题:构建城市-国家映射的Pandas DataFrame

我想要创建一个Pandas DataFrame,让每个城市对应其所属国家,最终DataFrame需要包含4列:Country、City、ImrByCountry、PopulationByCity,而非当前输出的3列(Country、IMRperCountry、PopulationByCountry)。我写了下面的代码,但把生成的字典转换成DataFrame时没能成功:

import pandas as pd

data = {}

for country in root.findall("country"):
    country_name = country[0].text
    imr = country.findtext('infant_mortality')
    population = country.findtext("./population[@year='2011']")

    cities_in_country = {}

    for city in country.findall("city"):
        city_name = city[0].text
        city_population = city.findtext("./population[@year='2011']")
        cities_in_country[city_name] = city_population

    data[country_name] = {
        'IMR': imr,
        'Population': population,
        'City': cities_in_country
    }

内容的提问来源于stack exchange,提问作者Radion Nazmiev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:02:54