简体   繁体   中英

Pandas dataframe to dictionary of lists

Having a dataframe of the form:

element1   | element2  |  element3
cat           bird          plane
dog           poodle        cloud
pig           bike          sky

I want to convert it to a dictionary of lists of the form

{ 'element1' : ['cat', 'dog', 'pig'], 
  'element2' : ['bird', 'poodle', 'bike'],
  'element3' : ['plane', 'cloud', 'sky']  }

I am looking at the documentation of the .to_dict method, but none of the options seem to do what I need.

Usual to_dict bases on index elements as key values, so transpose your dataframe and apply list by row followed by dictionary conversion

df.T.apply(list,1).to_dict()

Out:

{'element1': ['cat', 'dog', 'pig'],
 'element2': ['bird', 'poodle', 'bike'],
 'element3': ['plane', 'cloud', 'sky']}

Use DataFrame.to_dict with list parameter:

d = df.to_dict('list')
print (d)
{'element1': ['cat', 'dog', 'pig'],
 'element2': ['bird', 'poodle', 'bike'], 
 'element3': ['plane', 'cloud', 'sky']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM