具有多个值的Pandas/Python映射字典键

具有多个值的Pandas/Python映射字典键,python,pandas,dictionary,Python,Pandas,Dictionary,我想知道如何将字典键映射到多个字典项。我尝试了下面的方法,但是输出不是预期的结果 d = {'col1': ['type 2','type 3', 'type 4', 'type 5', 'type 6', 'type 6']} df = pd.DataFrame(data=d) dict = { 'a' :['type 2', 'type 3'], 'b' : ['type 4', 'type 5'], 'c': ['types 6', 'types 7'] } f

我想知道如何将字典键映射到多个字典项。我尝试了下面的方法,但是输出不是预期的结果

d = {'col1': ['type 2','type 3', 'type 4', 'type 5', 'type 6', 'type 6']}
df = pd.DataFrame(data=d)

dict = {
    'a' :['type 2', 'type 3'],
    'b' : ['type 4', 'type 5'],
    'c': ['types 6', 'types 7']
}

for k, v in df.items():
    df['col1'].map({k: v})
    print(df)
预期产出:
我们可以尝试
爆炸

s = pd.Series(d).explode()
df['col1'] = df['col1'].map(dict(zip(s,s.index)))
输入


注意:不要将变量命名为与python或pandas中的原始函数相同的变量。您可能需要转换dict,使键为值,反之亦然

dd = {
    'a' :['type 2', 'type 3'],
    'b' : ['type 4', 'type 5'],
    'c': ['type 6', 'type 7']
}
ddd = {l:v for v,k in dd.items() for l in k}
print(ddd)
输出:

现在你可以很容易地绘制地图了

df.col1.map(ddd)
输出:

{'type 2': 'a',
 'type 3': 'a',
 'type 4': 'b',
 'type 5': 'b',
 'type 6': 'c',
 'type 7': 'c'}
df.col1.map(ddd)
0    a
1    a
2    b
3    b
4    c
5    c
Name: col1, dtype: object