简体   繁体   中英

How to transform a pandas df to a complex json structure?

Current pandas dataframe:

people animal frequencies
Bob dog 2
Bob cat 1
Bob parrot 1
Kate dog 1
Kate parrot 1
Joy cat 3

Desired output (this json dictionary):

dictionary={'title': 'frequencies',
            'children': [{'animal': 'dog', 'people': [{'name': 'Bob', 'freq': 2}, {'name':'Kate', 'freq': 1}]},
                         {'animal': 'cat', 'people': [{'name': 'Bob', 'freq': 1}, {'name':'Joy', 'freq': 3}]},
                         {'animal': 'parrot', 'people': [{'name':'Kate', 'freq': 1}, {'name':'Bob', 'freq': 1}]}]}

For the moment, I have only managed transform the above pandas df to a list of dictionaries. I suppose this is how one would start? :

list_dicts = df.to_dict('records')

resulting in:

list_dicts = [{'people': 'Bob', 'animal': 'dog', 'frequencies': 2},
              {'people': 'Bob', 'animal': 'cat', 'frequencies': 1},
              {'people': 'Bob', 'animal': 'parrot', 'frequencies': 1},
              {'people': 'Kate', 'animal': 'dog', 'frequencies': 1},
              {'people': 'Kate', 'animal': 'parrot', 'frequencies': 1},
              {'people': 'Joy', 'animal': 'cat', 'frequencies': 3}]
>>> list_dicts = [{"people": "Bob", "animal": "dog", "frequencies": 2},
...               {"people": "Bob", "animal": "cat", "frequencies": 1},
...               {"people": "Bob", "animal": "parrot", "frequencies": 1},
...               {"people": "Kate", "animal": "dog", "frequencies": 1},
...               {"people": "Kate", "animal": "parrot", "frequencies": 1},
...               {"people": "Joy", "animal": "cat", "frequencies": 3}]
>>> 
>>> temp = defaultdict(list)
>>> for item in list_dicts:
...     temp[item["animal"]].append({"name": item["people"], "freq": item["frequencies"]})
... 
>>> result = {"title": "frequencies", "children":[
...     {"animal": animal, "people": people} for animal, people in temp.items()
... ]}
>>> result
{'title': 'frequencies', 'children': [{'animal': 'dog', 'people': [{'Bob': 2}, {'Kate': 1}]}, {'animal': 'cat', 'people': [{'Bob': 1}, {'Joy': 3}]}, {'animal': 'parrot', 'people': [{'Bob': 1}, {'Kate': 1}]}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM