Pandas: 使用多于 1 列的字典映射

Pandas: mapping with dict using more than 1 column

我得到了基本的 DataFrame:

df = pd.DataFrame([[1, 2],[3, 4],[5, 6],[7, 8]],
                  index=['A','B','C','D'], columns=['X','Y'])

我希望 map 函数在 X 和 Y 列上工作并获得:

   X  Y  Chk
A  1  2  found A
B  3  4  found B
C  5  6  found C
D  7  8  found D

为此,我为 2 个键创建了一个字典:

mapped = {1:{2:'found A'}, 3:{4:'found B'},5:{6:'found C'}, 7:{8:'found D'}}

并在 DataFrame 上使用了 applymap 方法:

df['Chk'] = df[['X','Y']].applymap(mapped)

不幸的是,我收到一条错误消息:

TypeError: ("'dict' object is not callable", 'occurred at index X')

是代码有误,还是dict-based映射根本不支持多于1列?

创建 DataFrame 然后 SeriesMultiIndexstack first and then join:

s = pd.DataFrame(mapped).stack().rename('Chk')
print (s)
2  1    found A
4  3    found B
6  5    found C
8  7    found D
Name: Chk, dtype: object

df = df.join(s, on=['Y','X'])
print (df)
   X  Y      Chk
A  1  2  found A
B  3  4  found B
C  5  6  found C
D  7  8  found D

如果可能,创建 DataFrame 进行映射,然后使用 merge:

mapped = {'X': [1, 3, 5, 7], 
         'Chk': ['found A', 'found B', 'found C', 'found D'],
         'Y': [2, 4, 6, 8]}

df1 = pd.DataFrame(mapped)
print (df1)
       Chk  X  Y
0  found A  1  2
1  found B  3  4
2  found C  5  6
3  found D  7  8

df = pd.merge(df, df1, how='left', on=['X','Y'])
print (df)
   X  Y      Chk
0  1  2  found A
1  3  4  found B
2  5  6  found C
3  7  8  found D