4

There's the pandas dataframe 'test_df'. My aim is to convert it to a dictionary. Therefore I run this:

   id   Name   Gender  Age  
0  1  'Peter'   'M'     32    
1  2  'Lara'    'F'     45   

Therefore I run this:

test_dict = test_df.set_index('id').T.to_dict()

The output is this:

{1: {'Name': 'Peter', 'Gender': 'M', 'Age': 32}, 2: {'Name': 'Lara', 'Gender': 'F', 'Age': 45}}

Now, I want to choose only the 'Name' and 'Gender' columns as the values of dictionary's keys. I'm trying to modify the above script into sth like this:

test_dict = test_df.set_index('id')['Name']['Gender'].T.to_dict()

with no success!

Any suggestion please?!

Dino C
  • 307
  • 3
  • 15

1 Answers1

7

You was very close, use subset of columns [['Name','Gender']]:

test_dict = test_df.set_index('id')[['Name','Gender']].T.to_dict()
print (test_dict)
{1: {'Name': 'Peter', 'Gender': 'M'}, 2: {'Name': 'Lara', 'Gender': 'F'}}

Also T is not necessary, use parameter orient='index':

test_dict = test_df.set_index('id')[['Name','Gender']].to_dict(orient='index')
print (test_dict)
{1: {'Name': 'Peter', 'Gender': 'M'}, 2: {'Name': 'Lara', 'Gender': 'F'}}
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Correct answer!Thanks a lot! – Dino C Dec 13 '16 at 13:50
  • This worked for me: node_df.set_index('kegg_cid')[['name', 'wt', 'vis']].T.to_dict('dict'). This gave me a dictionary of dictionaries of the form {'c00022': {'name': 'pyruvate', 'vis': 1, 'wt': 1}, 'c00024': {'name': 'acetyl-CoA', 'vis': 1, 'wt': 1}, ...}, where the first column gave the keys. The '-quoted strings are all df columns, so I needed to transpose the dataframe (see https://stackoverflow.com/a/56607013/1904943); I also had additional columns ('node', ...) in my dataframe, that I ignored (alternatively, you can slice the columns to derive a df with just the data you want). – Victoria Stuart Jul 16 '19 at 02:13