1

I have a pandas dataframe that I am trying to convert to a certain json format:

df = pd.DataFrame([['A',1,2,3],['B',2,3,4],['C','C',1,6],['D','D',9,7]], columns=['W','X','Y','Z'])

df.set_index('W', inplace=True, drop=True, append=False)

df
   X  Y  Z
W
A  1  2  3
B  2  3  4
C  C  1  6
D  D  9  7

I am looking to get a json output as follows:

output_json = {'A': {'X':1,'Y':2,'Z':3}, 'B': {'X':2,'Y':3,'Z':4}, 'C':{'Y':1,'Z':6}, 'D': {'Y':9,'Z':7} }

This is what I have tried but I can't get the desired result for 'C' and 'D' keys:

df.to_json(orient='index')
'{"A":{"X":1,"Y":2,"Z":3},"B":{"X":2,"Y":3,"Z":4},"C":{"X":"C","Y":1,"Z":6},"D":{"X":"D","Y":9,"Z":7}}'

How to fix this? Perhaps this is something straightforward that I am missing. Thanks.

1 Answer 1

2

You can first convert to_dict and then use nested dict comprehension for filtering only int values, last for json use dumps:

import json

d = df.to_dict(orient='index')
j = json.dumps({k:{x:y for x,y in v.items() if isinstance(y, int)} for k, v in d.items()})
print (j)
{"A": {"X": 1, "Y": 2, "Z": 3}, 
 "C": {"Y": 1, "Z": 6},
 "D": {"Y": 9, "Z": 7},
 "B": {"X": 2, "Y": 3, "Z": 4}}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad can help! Good luck!

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.