0

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
    }
}

2 Answers 2

1

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]}
Sign up to request clarification or add additional context in comments.

Comments

1

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)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.