【问题标题】:How to implement the same concept in Python?如何在 Python 中实现相同的概念?
【发布时间】:2020-05-02 15:36:33
【问题描述】:

所以这是在 pandas 数据框中排序的数据,我想使用 pathString 列中提到的层次结构创建一个像这样的 json(如下所示)。请告诉我,我可以在 python 中实现这个吗?

{
    "name":"world",
    "children":[
        {
            "name":"North America",
            "children":[
                {
                    "name":"Bermuda",
                    "continent":"North America",
                    "country":"Bermuda",
                    "GNI":106140,
                    "iso3":"BMU",
                    "population":67837
                    },
                {
                    "name":"United States",
                    "continent":"North America",
                    "country":"United States",
                    "GNI":55200,
                    "iso3":"USA",
                    "population":313973000
                    },
                {
                    "name":"Canada",
                    "continent":"North America",
                    "country":"Canada",
                    "GNI":51630,
                    "iso3":"CAN",
                    "population":33487208
                },
                {
                    "name":"Bahamas, The",
                    "continent":"North America",
                    "country":"Bahamas, The",
                    "GNI":20980,
                    "iso3":"BHS",
                    "population":309156
                    }
                    ]
        },
        {
            "name":"Europe",
            "children":[
                {
                    "name":"Norway","continent":"Europe","country":"Norway","GNI":103630,"iso3":"NOR","population":4676305
                },
                {
                    "name":"Switzerland","continent":"Europe","country":"Switzerland","GNI":88120,"iso3":"CHE","population":7604467
                },
                {"name":"Luxembourg","continent":"Europe","country":"Luxembourg","GNI":75990,"iso3":"LUX","population":491775
                }
                ]
        }

    ]}

我尝试使用递归,但无法正确实现。伙计们,如果可以的话,请帮助我,我被这个问题困扰了很长时间!如果可能,需要一些快速帮助!提前致谢!

【问题讨论】:

    标签: python r json pandas dataframe


    【解决方案1】:

    如果你拆分 pathString 列会容易得多,这样你就会有更多的 3 列:

    World | Continent | Country
    

    通过这些列,您可以应用 groupby 并使用 to_json

    (
       df.groupby(['World','Continent','Country'], as_index=False)
       .reset_index()
       .to_json(orient='records'))
    )
    

    下次请把表格文件的链接放在这里,方便帮助你。

    【讨论】:

    • 感谢您的回答,当我尝试实现您的方法时,我收到此错误:“无法访问 'DataFrameGroupBy' 对象的可调用属性 'to_json',请尝试使用 'apply' 方法”
    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2014-07-15
    • 2012-06-20
    • 1970-01-01
    相关资源
    最近更新 更多