Pandas - 从列表中的字典值映射列

cin*_*n21 3 python pandas

我有一个简单的 DataFrame 和一个字典,如:

import pandas as pd

dict = {'x' : ['a', 'c'], 'y': ['b', 'd']}
df = pd.DataFrame({'col1': {0: 'a', 1: 'b', 2: 'c', 3:'d'}})

  col1
0    a
1    b
2    c
3    d
Run Code Online (Sandbox Code Playgroud)

现在我想对字典进行“反向映射”以获得另一个“col2”,以及像这样的 DataFrame:

  col1 col2
0    a    x
1    b    y
2    c    x
3    d    y
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Jar*_*děk 6

您可以通过使用字典理解pandas.Series.map()方法来实现它。代码如下。

>>> df['col2'] = df.col1.map({item: k for k, v in dict.items() for item in v})
>>> print(df)

  col1 col2
0    a    x
1    b    y
2    c    x
3    d    y
Run Code Online (Sandbox Code Playgroud)