4

I have a dataframe with columns ['a', 'b', 'c' ] and would like to export in dictionnary as follow :

{ 'value of a'   :  { 'b': 3, 'c': 7},
  'value2 of a'  :  { 'b': 7, 'c': 9}
}

1 Answer 1

4

I believe you need set_index with DataFrame.to_dict:

df = pd.DataFrame({'a':list('ABC'),
                   'b':[4,5,4],
                   'c':[7,8,9]})

print (df)
   a  b  c
0  A  4  7
1  B  5  8
2  C  4  9

d = df.set_index('a').to_dict('index')
print (d)
{'A': {'b': 4, 'c': 7}, 'B': {'b': 5, 'c': 8}, 'C': {'b': 4, 'c': 9}}

And for json use DataFrame.to_json:

j = df.set_index('a').to_json(orient='index')
print (j)
{"A":{"b":4,"c":7},"B":{"b":5,"c":8},"C":{"b":4,"c":9}}
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.