用一个数据帧替换pandas中的单词与其他数据帧中的单词

时间:2017-04-05 10:42:47

标签: python pandas dataframe

我有两个数据帧

(Pdb) df
                msg
0               the
1               wi
2               fi
3              **a/c**

(Pdb) dictionary

           old_msg    new_msg
0              a/c    account 
1             extend  extend
2             bal     balance

我希望第一个数据帧变为如下(用第二个数据帧替换单词)

(Pdb) df
          msg
0              the
1               wi
2               fi
3              **account**

1 个答案:

答案 0 :(得分:1)

您可以Seriesdict使用replace

df['msg'] = df['msg'].replace(dictionary.set_index('old_msg')['new_msg'])
print (df)
       msg
0      the
1       wi
2       fi
3  account

或者:

df['msg'] = df['msg'].replace(dictionary.set_index('old_msg')['new_msg'].to_dict())
print (df)
       msg
0      the
1       wi
2       fi
3  account