0

I have a dataframe like below. My question is transforming this into a nested JSON structure like below.

class code hasAttribute
XYZ ABC Y
XYZ BCD N
XYY CDE Y
[
  {
    "class": 'XYZ',
    "series": [
      {
        'Code': 'ABC',
        'hasAttribute': 'Y'
      }, 
      {
        'Code': 'BCD',
        'hasAttribute': 'N'
      }
    ]
  },
  {
    "class": 'XYY',
    "series": [
      {
        'Code': 'CDE',
        'hasAttribute': 'Y'
      }
    ]
  }
]

Here series consists of 'Code' and 'hasAttribute' so each code has either 'Y' or 'N' attribute.

1 Answer 1

2

You can use groupby and then use to_dict to form each group accordingly:

lst = df.groupby('class').apply(lambda x: {'class': x['class'].unique()[0], 'series': x.drop('class', axis=1).to_dict('records')}).tolist()

Output:

>>> lst
[
  {
    'class': 'XYY',
    'series': [
      {
        'Code': 'CDE',
        'hasAttribute': 'Y'
      }
    ]
  },
  {
    'class': 'XYZ',
    'series': [
      {
        'Code': 'ABC',
        'hasAttribute': 'Y'
      },
      {
        'Code': 'BCD',
        'hasAttribute': 'N'
      }
    ]
  }
]
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.