Converting a dataframe to dictionary with multiple values

2024/10/15 5:23:07

I have a dataframe like

Sr.No   ID       A         B          C         D1     Tom     Earth    English      BMW2     Tom     Mars     Spanish      BMW       Green          3     Michael Mercury  Hindi        Audi      Yellow4     John    Venus    Portugese    Mercedes  Blue5     John             German       Audi      Red

I am trying to convert this to a dictionary by ID like :

{'ID' : 'Tom', 'A' : ['Earth', 'Mars'], 'B' : ['English', 'Spanish'], 'C' : ['BMW', 'BMW'], 'D':['Green'] }, {'ID' : 'Michael', 'A' : ['Mercury'], 'B' : ['Hindi'], 'C' : ['Audi'],'D':['Yellow']},{'ID' : 'John', 'A' : ['Venus'], 'B' : ['Portugese', 'German'], 'C' : ['Mercedes', 'Audi'], 'D':['Blue', 'Red'] }

This is somewhat similar to what I want.

I also tried ,

df.set_index('ID').to_dict()

but this gives me dictionary of length 5 instead of 3. Any help would be appreciated.

Answer

Grouping by 'ID' and apply to_dict to each group with orient='list' comes pretty close:

df.groupby('ID').apply(lambda dfg: dfg.to_dict(orient='list')).to_dict()
Out[25]: 
{'John': {'A': ['Venus', nan],'B': ['Portugese', 'German'],'C': ['Mercedes', 'Audi'],'D': ['Blue', 'Red'],'ID': ['John', 'John'],'Sr.No': [4, 5]},'Michael': {'A': ['Mercury'],'B': ['Hindi'],'C': ['Audi'],'D': ['Yellow'],'ID': ['Michael'],'Sr.No': [3]},'Tom': {'A': ['Earth', 'Mars'],'B': ['English', 'Spanish'],'C': ['BMW', 'BMW'],'D': [nan, 'Green'],'ID': ['Tom', 'Tom'],'Sr.No': [1, 2]}}

It should just be a matter of formatting the result slightly.

Edit: to remove 'ID' from the dictionaries:

df.groupby('ID').apply(lambda dfg: dfg.drop('ID', axis=1).to_dict(orient='list')).to_dict()
Out[5]: 
{'John': {'A': ['Venus', nan],'B': ['Portugese', 'German'],'C': ['Mercedes', 'Audi'],'D': ['Blue', 'Red'],'Sr.No': [4, 5]},'Michael': {'A': ['Mercury'],'B': ['Hindi'],'C': ['Audi'],'D': ['Yellow'],'Sr.No': [3]},'Tom': {'A': ['Earth', 'Mars'],'B': ['English', 'Spanish'],'C': ['BMW', 'BMW'],'D': [nan, 'Green'],'Sr.No': [1, 2]}}
https://en.xdnf.cn/q/69326.html

Related Q&A

How do I create KeyPoints to compute SIFT?

I am using OpenCV-Python.I have identified corner points using cv2.cornerHarris. The output is of type dst.I need to compute SIFT features of the corner points. The input to sift.compute() has to be of…

Error in Tensorboards(PyTorch) add_graph

Im following this Pytorchs Tensorboard documentation. I have the following code: model = torchvision.models.resnet50(False) writer.add_graph(model)It throws the following error:_ = model(*args) # dont…

Population must be a sequence or set. For dicts, use list(d)

I try to excute this code and I get the error bellow, I get the error in the random function and I dont know how to fix it, please help me.def load_data(sample_split=0.3, usage=Training, to_cat=True, v…

Why do imports fail in setuptools entry_point scripts, but not in python interpreter?

I have the following project structure:project |-project.py |-__init__.py |-setup.py |-lib|-__init__.py|-project|-__init__.py|-tools.pywith project.py:from project.lib import *def main():print("ma…

msgpack unserialising dict key strings to bytes

I am having issues with msgpack in python. It seems that when serialising a dict, if the keys are strings str, they are not unserialised properly and causing KeyError exceptions to be raised.Example:&g…

Better solution for Python Threading.Event semi-busy waiting

Im using pretty standard Threading.Event: Main thread gets to a point where its in a loop that runs:event.wait(60)The other blocks on a request until a reply is available and then initiates a:event.set…

\ufeff Invalid character in identifier

I have the following code :import urllib.requesttry:url = "https://www.google.com/search?q=test"headers = {}usag = Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefo…

Python multiprocessing - Passing a list of dicts to a pool

This question may be a duplicate. However, I read lot of stuff around on this topic, and I didnt find one that matches my case - or at least, I didnt understood it.Sorry for the inconvenance.What Im tr…

Failed to write to file but generates no Error

Im trying to write to a file but its not working. Ive gone through step-by-step with the debugger (it goes to the write command but when I open the file its empty).My question is either: "How do I…

train spacy for text classification

After reading the docs and doing the tutorial I figured Id make a small demo. Turns out my model does not want to train. Heres the codeimport spacy import random import jsonTRAINING_DATA = [["My l…