-2

My dataframe from xlsx:

1  NaN  A     B     C
2  X   '1'   '11'  '111'
3  Y   '2'   '22'  '222'
4  Z   '3'   '33'  '333'

How to use pandas to convert to dict type like:

{X:{'A':'1','B':'11','C':'111'},
 Y:{'A':'2','B':'22','C':'222'},
 Z:{'A':'3','B':'33','C':'333'}}
bellfeige
  • 11
  • 4
  • This question has already been answered here: https://stackoverflow.com/questions/18695605/python-pandas-dataframe-to-dictionary – Muriel Jan 18 '21 at 15:42
  • This question seems to be repetitive and has been answered in stack overflow. Please refer to this link: https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary. – sheida Jan 18 '21 at 15:48

2 Answers2

0

There is a simple function for this:

df.to_dict()
gtomer
  • 5,643
  • 1
  • 10
  • 21
0

Try this:

df.set_index('id').T.to_dict('records')

Its what I use...

audittxl
  • 41
  • 1
  • 12