使用不同的地图同时映射多个列

Aar*_*and 2 python dictionary pandas

我这里有一个 pandas 数据框:

import pandas as pd

df = pd.DataFrame({'col1': ['a','a','b','b'],
                   'col2': ['a','a','b','b']})
Run Code Online (Sandbox Code Playgroud)

我这里有一个映射字典:

dict_map = {'col1': {'a': 0.5, 'b': 1.0},
            'col2': {'a': 0.6, 'b': 0.9}}
Run Code Online (Sandbox Code Playgroud)

我想将每一列与相应的字典映射,以便数据框看起来像:

    col1  col2
0   0.5   0.6
1   0.5   0.6
2   1.0   0.9
3   1.0   0.9
Run Code Online (Sandbox Code Playgroud)

我可以轻松地迭代其中的列df并获得所需的结果,但我试图避免迭代。我怎样才能在不迭代的情况下做到这一点?

小智 5

您可以使用pandas.DataFrame.replace

df = df.replace(dict_map)
Run Code Online (Sandbox Code Playgroud)

输出:

>>> df
   col1  col2
0   0.5   0.6
1   0.5   0.6
2   1.0   0.9
3   1.0   0.9
Run Code Online (Sandbox Code Playgroud)