将特定字段从数据帧转换为python中的字典

时间:2018-04-05 06:58:32

标签: python pandas dictionary

我有以下数据:

Parent_Attribute    Attribute       Y/N for Modelling   Impute_Value    Type    Product     Description
age                     age             YES             Unknown         CAT     Multiple    ecohorts
bill_other          bill_other_m0       YES                 0           CAT     Multiple    Billing (other)
bill_other          bill_other_m1       YES                 0           CAT     Multiple    Billing (other)
bill_other          bill_other_m2       YES                 0           CAT     Multiple    Billing (other)
bill_other          bill_other_m3       YES                 0           CAT     Multiple    Billing (other)
bill_other          bill_other_m4       YES                 0           CAT     Multiple    Billing (other)

所有这些都需要存储在字典中,其中属性是键,剩余列值作为该键的值:

attribute : ['parent_attribute,Y/N Modelling,Impute_Value,Type,Product,Description] 

必须对数据帧的每一行进行此操作。

完成的字典看起来像。

{                       
    age             :['age',"Yes","Unknown","CAT","Multiple","ecohorts"]                    
    bill_other_m0   :["bill_other","Yes",0,"CAT","Multiple","Billing(Other)"]                   
    bill_other_m1   :["bill_other","Yes",0,"CAT","Multiple","Billing(Other)"]                   
    bill_other_m2   :["bill_other","Yes",0,"CAT","Multiple","Billing(Other)"]                   
    bill_other_m3   :["bill_other","Yes",0,"CAT","Multiple","Billing(Other)"]                   
    bill_other_m4   :["bill_other","Yes",0,"CAT","Multiple","Billing(Other)"]                   
}

我经历了dataframe.to_dict,但似乎只是使用它会有助于我的目的。 有人可以指导我吗?

1 个答案:

答案 0 :(得分:2)

似乎需要:

d = df.set_index('Attribute').T.to_dict('l')