【问题标题】:Transform dataframe to nested dictionary将数据框转换为嵌套字典
【发布时间】:2019-08-12 11:51:55
【问题描述】:

我正在尝试将数据框转换为嵌套字典,但到目前为止没有成功。 我的数据框如下所示:

    _id                     date        predicted_date  code    type    predicted_value
5d223332216e3b4d587204db    2010-12-31  2011-12-31      70      delta   140
5d223332216e3b4d587204db    2016-12-31  2017-12-31      70      delta   360
5d223506216e3b4d587204dc    2008-12-31  2009-12-31      70      delta   40
5d223506216e3b4d587204dc    2009-12-31  2010-12-31      70      delta   55
5d223506216e3b4d587204dc    2010-12-31  2011-12-31      70      delta   70

我想要一本这样的字典:

    {
        "_id":"5d223332216e3b4d587204db",
        "delta":[
            {
                "date":2010-12-31,
                "data":{
                    "70":140
                }
            },
            {
                "date":2016-12-31,
                "data":{
                    "70":360
                }
            }
        ]   
    },
    {
        "_id":"5d223506216e3b4d587204dc",
        "delta":[
            {
                "date":2008-12-31,
                "data":{
                    "70":40
                }
            },
            {
                "date":2009-12-31,
                "data":{
                    "70":55
                }
            },
            {
                "date":2010-12-31,
                "data":{
                    "70":70
                }
            }
        ]   
    }

我尝试使用 groupby()、apply()、lambda 函数、to_dict()...我没有得到预期的结果。

有什么帮助吗?

非常感谢,

西蒙

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    您可以混合使用groupby 和列表理解。您还可以将解析分解为更小的函数并将它们放入一个类中。

    class Converter:
        """ convert a DataFrame to nested dict structure"""
    
        @staticmethod
        def _row_to_dict(row):
            return {  
                "date": row.date,
                "data": {
                    str(row.code): row.predicted_value
                }
            }
    
        @staticmethod
        def _group_to_dict(_id, group):
            return {
                "_id": _id,
                "delta": [Converter._row_to_dict(row) for _, row in group.iterrows()]
            }
    
        @staticmethod
        def to_dict(df):
            return [
                Converter._group_to_dict(_id, group) 
                for _id, group in df.groupby('_id')
            ]
    
    Converter.to_dict(df)  
    

    输出:

    [{'_id': '5d223332216e3b4d587204db',
      'delta': [{'data': {'70': 140}, 'date': '2010-12-31'},
       {'data': {'70': 360}, 'date': '2016-12-31'}]},
     {'_id': '5d223506216e3b4d587204dc',
      'delta': [{'data': {'70': 40}, 'date': '2008-12-31'},
       {'data': {'70': 55}, 'date': '2009-12-31'},
       {'data': {'70': 70}, 'date': '2010-12-31'}]}]
    

    【讨论】:

    • 太好了!非常感谢!我只需要改变一个小东西,因为“delta”不必是硬编码的。该函数只需要获取“类型”列的值。再次感谢
    猜你喜欢
    • 2014-05-10
    • 2021-11-28
    • 2022-01-07
    • 1970-01-01
    • 2021-08-30
    • 2018-08-14
    • 2015-10-06
    • 2019-09-06
    相关资源
    最近更新 更多