Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas Dataframe to Tuple Dictionary

I would like to create a tuple dictionary of a dataframe. Currently, I have a dataframe looking like this:


xxxxxxxxx | Period 1 | Period 2 |
Customer  | -------- | -------- |
Customer 1| 31       | 222      |
Customer 2| 46       | 187      |

I would like to get a tuple dictionary of this:

tuple_dict = 
{('Customer 1', 'Period 1'): 31,
 ('Customer 2', 'Period 1'): 46, 
 ('Customer 1', 'Period 2'): 222, 
 ('Customer 2', 'Period 2'): 187} 

It is probably posted somewhere already but I can’t find it unfortunately. Could somebody help me?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Currently I converted the above looking table to a dictionary with

dict = df.to_dict(): 

This created 4 seperate dictionaries (one for each period),

Period 1: {'Customer 1': 31, 'Customer 2': 46}
Period 2: {'Customer 1': 222 ,'Customer 2': 187}

But I really would like to have tuple dictionaries as described above. Thank you so much for helping!

>Solution :

Try:

print(df.stack().to_dict())

Prints:

{
    ("Customer 1", "Period 1"): 31,
    ("Customer 1", "Period 2"): 222,
    ("Customer 2", "Period 1"): 46,
    ("Customer 2", "Period 2"): 187,
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading