Home > Enterprise >  convert dataframe cols as dict key and values
convert dataframe cols as dict key and values

Time:05-16

I have a dataframe like as below

 Name,correct_name
  Test Level,Test
  Test Lvele,Test
  dummy Inc,dummy
  dummy Pvt Inc,dummy
  dasho Ltd,dasho
  dasho PVT Ltd,dasho
  delphi Ltd,delphi
  delphi pvt ltd,delphi

I would like to convert the dataframe to dict but in a different format.

For ex: I tried the below

map_df.to_dict()

but this results in format that is not useful for me.

However, I expect my output to be like as below

{'Test Level': 'Test',
 'Test Lvele': 'Test',
 'dummy Inc': 'dummy',
 'dummy Pvt Inc': 'dummy',
 'dasho Ltd': 'dasho',
 'dasho PVT Ltd': 'dasho',
 'delphi Ltd': 'delphi',
 'delphi pvt ltd': 'delphi'}

CodePudding user response:

You can do this using 3 methods. Answering my own question for the benefit of others

dict(zip(map_df.Name, map_df.correct_name))  # option 1

or 

pd.Series(map_df.correct_name.values,index=map_df.raw_name).to_dict()  #option 2

or 

map_df.set_index('raw_name').to_dict()['correct_name']  #option 3


{'Test Level': 'Test',
 'Test Lvele': 'Test',
 'dummy Inc': 'dummy',
 'dummy Pvt Inc': 'dummy',
 'dasho Ltd': 'dasho',
 'dasho PVT Ltd': 'dasho',
 'delphi Ltd': 'delphi',
 'delphi pvt ltd': 'delphi'}
  • Related