I am currently fetching data from an RestAPI which I then want to process. However, the platform I use needs the data to be transformed with the pandas dataframe. In order to get it into the correct format, I need to transform this response:
data = {
"apple":{
"price": 0.89,
"category": "fruit",
"weight": 13.88
},
"carrot":{
"price": 1.87,
"category": "vegetable",
"weight": 3.23
}
}
into this format:
data = {
"product": {
"apple",
"carrot"
},
"price": {
0.89,
1.87
},
"category": {
"fruit",
"vegetable"
},
"weight": {
13.88,
3.23
}
}
>Solution :
You can use:
df = pd.DataFrame(data)
out = df.T.rename_axis('product').reset_index()
output:
product price category weight
0 apple 0.89 fruit 13.88
1 carrot 1.87 vegetable 3.23
as dictionary:
out = df.T.rename_axis('product').reset_index().to_dict('list')
output:
{'product': ['apple', 'carrot'],
'price': [0.89, 1.87],
'category': ['fruit', 'vegetable'],
'weight': [3.23, 13.88]}