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.