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

Convert dictionary of sets to pandas dataframe

I have a dictionary of sets in python, something like:

{'+++': {'---', '--0', '-00', '0--', '00-', '000'}, '0++': {'+--', '+0-', '---', '--0', '-00', '0--', '00-', '000'}}

and I want to convert this into a pandas dictionary, with two columns: the first being the indices of the dictionary and the 2nd, being the set of strings. When I try to do this with Dataframe.from_dict, pandas creates as many columns as the max number of strings in a set.

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

>Solution :

I think you should surround your value in dict by list.

import pandas as pd
test_dict = {
    "+++": {"---", "--0", "-00", "0--", "00-", "000"},
    "0++": {"+--", "+0-", "---", "--0", "-00", "0--", "00-", "000"},
}
for key, value in test_dict.items():
    test_dict[key] = [value]
print(test_dict)

then your dict change to this:

{
    "+++": [{"00-", "-00", "---", "0--", "--0", "000"}],
    "0++": [{"00-", "-00", "---", "+--", "0--", "+0-", "--0", "000"}],
}

last, use from_dict:

test_df = pd.DataFrame.from_dict(test_dict, orient="index").reset_index()
print(test_df)

this is the result.

index                                         0
0   +++            {00-, -00, ---, 0--, --0, 000}
1   0++  {00-, -00, ---, +--, 0--, +0-, --0, 000}
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