How to transform Array into CSV Format in Python using DataFrame?

Question:

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
    }
}
Asked By: cinemandre

||

Answers:

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]}
Answered By: mozway

you can use pandas as in the answer suggested by @mozway
and you can also do it without it, and without any additional library

# first create a "product" key for each product
data = [{"product":key, **value} for key,value in data.items()]

# then format it the way you want
formatted = {}
for k in data[0].keys():
  formatted[k] = tuple(d[k] for d in data)

print(formatted)

The output would be

{'product': ('apple', 'carrot'),
 'price': (0.89, 1.87),
 'category': ('fruit', 'vegetable'),
 'weight': (13.88, 3.23)}
Answered By: Seddik Mekki
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.