MrSimple
MrSimple

Reputation: 43

Convert columns of DataFrame into dictionary keys

I was trying to convert three columns of DataFrame into dictionary keys.

I was trying to use loop to convert each column and track the blood types of the workers. Blood types shouldn't repeat itself.

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

I am expecting the following.

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

Upvotes: 1

Views: 52

Answers (1)

BENY
BENY

Reputation: 323226

Here we using stack to create the new key , then 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]}

Upvotes: 2

Related Questions