0

I have a dataframe df like below:

col1 | col2| col3| col4| col5
_____|_____|_____|_____|______
 1   |  X  |  A  |  a  |  x
 1   |  X  |  B  |  b  |  y

I need to convert it as below:

{'col1':'1', 'col2':'X' , 'A':{ 'col4':'a', 'col5':'x'}, 'B':{'col4':'b', 'col5':'y'}}

I have tried with below code:

json= df.groupby(['col1,'col2'],as_index='False')[['col3','col4','col5']]
                   .apply(lambda x:x.set_index('col3').to_dict(orient='index'))
                   .reset_index()
                   .to_json(orient='records'))

And it gives me output:

[{'col1':'1', 'col2':'X' ,'0':{ 'A':{ 'col4':'a', 'col5':'x'}, 'B':{'col4':'b', 'col5':'y'} }}]

I have tried using to_dict in place of to_json but it does not work as well. Above is the closest I came to meeting my requirement. I am assuming the '0' represents the index. Is there any way to remove it?

1
  • What do you want to remove? Commented Nov 24, 2019 at 13:40

1 Answer 1

1

Use:

json= (df.groupby(['col1','col2','col3'],as_index='False')[['col4','col5']]
                   .apply(lambda x: dict(x.values))
                   .unstack()
                   .reset_index()
                   .to_json(orient='records')
)
print (json)
[{"col1":1,"col2":"X","A":{"a":"x"},"B":{"b":"y"}}]
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.