1

Eg. My results are returned in this format

    "name": {
      "1": "bill",
      "2": "mike",
      "3": "dave"
    },
    "age": {
      "1": 20,
      "2": 21,
      "3": 40
    },

but I would prefer the following format

    "name": [
     "bill",
      "mike",
      "dave"
    ],
    "age": [
      20,
      21,
      40
    ],
3
  • if you are exporting the dataframe to JSON ? if yes then give index=False while exporting Commented Oct 26, 2021 at 15:46
  • I've tried that but 'index=False' is only valid when 'orient' is 'split' or 'table' Commented Oct 26, 2021 at 16:02
  • Use to_dict() with orient='list' then convert dict to JSON with double quotes. See my answer for details. Commented Oct 26, 2021 at 16:31

1 Answer 1

1

The Pandas function DataFrame.to_dict() has an option orient='list' that outputs the layout you want.

The only difference is that it outputs a dict with single quote instead of JSON with double quotes. You can further convert the dict to JSON, e.g. as follows:

class dict2JSON(dict):
    def __str__(self):
        return json.dumps(self)

    def __repr__(self):
        return json.dumps(self)

result =  dict2JSON(df.to_dict(orient='list')) 

Demo

data = {'name': {1: 'bill', 2: 'mike', 3: 'dave'}, 'age': {1: 20, 2: 21, 3: 40}}
df = pd.DataFrame(data)

print(df.to_json(orient='columns'))

# Old Output 
{"name":{"1":"bill","2":"mike","3":"dave"},"age":{"1":20,"2":21,"3":40}}


# Run new codes:
class dict2JSON(dict):
    def __str__(self):
        return json.dumps(self)

    def __repr__(self):
        return json.dumps(self)

result =  dict2JSON(df.to_dict(orient='list')) 

print(result)

# New Output
{"name": ["bill", "mike", "dave"], "age": [20, 21, 40]}
Sign up to request clarification or add additional context in comments.

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.