简体   繁体   中英

How do we create a dictionary from a dataframe?

dataframe is like below:

ENV   INVOCATION SSM_ID ANA_ID   VALUE  
env1   invo1      A      oas      1.6  
env1  invo1      A      default  2.0  
env1  invo1      B      oas      0.8  
env1  invo2      C      oas      0.4  
env2  invo1      A      oas      3.1  
env2  invo2      B      default  0.6  

I want a dictionary like below

dic = {(env1,invo1,A,oas) : 1.6 , (env1,invo1,A,default) : 2.0 , (env1,invo1,B,oas) : 0.8 , (env1,invo2,C,oas) : 0.4 , (env2,invo1,A,oas) : 3.1 , (env2,invo2,B,default) : 0.6 }

Just set_index to all the columns except VALUE:

print (df.set_index(list(df.columns[:-1]))["VALUE"].to_dict())

{('env1', 'invo1', 'A', 'oas'): 1.6,
 ('env1', 'invo1', 'A', 'default'): 2.0,
 ('env1', 'invo1', 'B', 'oas'): 0.8,
 ('env1', 'invo2', 'C', 'oas'): 0.4,
 ('env2', 'invo1', 'A', 'oas'): 3.1,
 ('env2', 'invo2', 'B', 'default'): 0.6}

跑:

dict = df.set_index(['ENV', 'INVOCATION', 'SSM_ID', 'ANA_ID']).VALUE.to_dict()

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