将DataFrame的列转换为字典键

时间:2019-04-18 00:30:33

标签: python pandas dataframe dictionary

我试图将DataFrame的三列转换为字典键。

我试图使用循环转换每一列并跟踪工人的血型。血型不应该重复。

Name = df[:,['Name1','Name2','Name3']] 
Names = {}
Bloodtypes = {}
for i,key,key2 in enumerate(zip(...)):
    if key  in Names[key] and key in Blood types[key]:
        Names[key].append(i)
        Blood types[key].append(key2)
    else:
        Names[key]=[i]
        Blood types[key]=[key2]

     Blood Type    Name1    Name2    Name3
0    A             NaN       NaN      John
1    O             Adam     Smith     NaN
2    B             NaN      John       NaN   
3    AB            NaN       NaN       NaN
4    A             NaN       NaN       NaN
5    B             NaN       NaN       NaN

我期望以下。

 Bloodtypes = {"Blank":['AB','A','B'],""John":['A','B'],("Adam","Smith"):['O']}
 Names = {"Blank":[3,4,5],""John":[0,2],("Adam","Smith"):[1]}

1 个答案:

答案 0 :(得分:2)

这里我们使用stack创建新密钥,然后使用groupby to_dict

df['Newkey']=df[['Name1','Name2','Name3']].stack().groupby(level=0).apply(tuple)
df.Newkey=df.Newkey.fillna('Blank')
df.groupby('Newkey')['BloodType'].apply(list).to_dict()
Out[471]: {'Blank': ['AB', 'A', 'B'], ('John',): ['A', 'B'], ('Adam', 'Smith'): ['O']}
df.reset_index().groupby('Newkey')['index'].apply(list).to_dict()
Out[472]: {'Blank': [3, 4, 5], ('John',): [0, 2], ('Adam', 'Smith'): [1]}