Reputation: 6132
So, today I'm struggling with the following situation: I have a dictionary where each key is a cluster number, and each value is a list comprised of the index numbers associated to that cluster:
dic={'0':[0,1,2],'1':[3,4,5]}
And my DataFrame looks like this:
index col
0 foo
1 foo
2 foo
3 foo
4 foo
5 foo
I thought the following would work:
df['cluster']=df.index.map(dic)
But it maps to the keys and not the values, bringing the following:
index col cluster
0 foo [0,1,2]
1 foo [3,4,5]
2 foo nan
3 foo nan
4 foo nan
5 foo nan
And what I want is:
index col cluster
0 foo 0
1 foo 0
2 foo 0
3 foo 1
4 foo 1
5 foo 1
Is there any other way than reversing my dictionary to map this?
Upvotes: 1
Views: 248
Reputation: 323306
Check with flatten your dict
df.index.map({y : x[0] for x in dic.items() for y in x[1]})
Out[379]: Index(['0', '0', '0', '1', '1', '1'], dtype='object')
#df['cluster']=df.index.map({y : x[0] for x in dic.items() for y in x[1]})
Upvotes: 2