假设我有以下DataFrame和字典:
df = pd.DataFrame({'group_col':['g1','g1','g1','g1','g2','g2','g2','g2'], 'map_col': ['a','b','c','d','a','b','c','d'], 'replace_col':[1,2,3,4,5,6,7,8]})
map_dict = {'a': 'b', 'c': 'd'}
下面是df
条:
group_col map_col replace_col
0 g1 a 1
1 g1 b 2
2 g1 c 3
3 g1 d 4
4 g2 a 5
5 g2 b 6
6 g2 c 7
7 g2 d 8
我想根据map_col
对分组列group_col
中的每个组使用map_dict
的映射来替换replace_col
中的值,获得以下数据帧:
group_col map_col replace_col
0 g1 a 2
1 g1 b 2
2 g1 c 4
3 g1 d 4
4 g2 a 6
5 g2 b 6
6 g2 c 8
7 g2 d 8
对于要进行多个组和替换的大型数据帧,最佳/最快的方法是什么?假设map_col
中的条目在每个组内不重复(如上例所示).