Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas to dictionary defining the columns used fo the key values

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?!

like image 269
Dino C Avatar asked Oct 28 '25 09:10

Dino C


1 Answers

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'}}
like image 97
jezrael Avatar answered Oct 31 '25 05:10

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!