Home > front end >  transfer a dic with a list in it into a dataframe
transfer a dic with a list in it into a dataframe

Time:07-13

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:

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

CodePudding user response:

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.

CodePudding user response:

Instead of pd.DataFrame, use pd.DataFrame.from_dict and set orient argument as index and apply transpose to the obtained dataframe

CODE

data = pd.DataFrame.from_dict(result, orient="index").transpose()

CodePudding user response:

You don't need to transpose, you can directly load the dict as a list containing a dict this way:

data=pd.DataFrame([result])
  • Related