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

transfer a dic with a list in it into a dataframe

I am reading an API and trying to transfer the response into a dataframe. The response I am getting is a dic with a list in it and I am not sure how to handle that

{‘instance_id’: -1, ‘segment_id’: 9000001395, ‘list 1’: [0.0, 100.0, 0.0], ‘list 2’: [0.0, 0.0, 100.0, 0.0, 0.0], ‘v85’: 11.5}

I have already tried the below but I am getting an error saying that the length of values does not match the length of the index:

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

data=pd.DataFrame(result,index=[0])

I am trying to get the data in this shape:

instance_id segment_id list 1 list 2 v85
-1 9000001395 [0.0, 100.0, 0.0] [0.0, 0.0, 100.0, 0.0, 0.0] 11.5

>Solution :

The reason you’re getting the error is because Pandas is attempting to create a column for each item in your result dictionary. The key of each item is used as the column label, the value is used as the list of values. The problem comes where columns are created that have different lengths.

Instead you can just do df = pd.DataFrame([result]). Putting the dictionary inside a list means Pandas expects a list of rows. Your list only has a single element, so a single row is created.

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