4

I have a dataframe

df:

    cola    colb   colc   cold
0      0    'a'     'b'   'c'
1      1    'd'     None  None
2      2    'g'     'h'   None

I want to convert it into dict where index are keys and list of column values are values like below:

d = {0 : [0,'a','b','c'], 1: [1,'d'], 2: [2,'g','h'] }

What I tried:

df.to_dict(orient='index')

I also tried with other values in orient parameters but nothing worked.

EDIT:

I want to ignore the NULL values in dictionary like shown in output.

Sociopath
  • 13,068
  • 19
  • 47
  • 75

1 Answers1

8

Use DataFrame.to_dict with orient='list', only before transpose DataFrame:

d = df.T.to_dict(orient='list')
print (d)
{0: [0, 'a', 'b', 'c'], 1: [1, 'd', 'e', 'f'], 2: [2, 'g', 'h', 'i']}

EDIT:

d = df.stack().groupby(level=0).apply(list).to_dict()
print (d)
{0: [0, 'a', 'b', 'c'], 1: [1, 'd'], 2: [2, 'g', 'h']}

Or:

d = {k:[x for x in v if x is not None] for k, v in df.T.to_dict(orient='list').items()}
print (d)
{0: [0, 'a', 'b', 'c'], 1: [1, 'd'], 2: [2, 'g', 'h']}
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • the edit version worked for me, i don't believe `to_dict(orient='list')` will give the desired result – Kenan May 24 '21 at 20:44