胡说叔叔
尝试这个:>>> import pandas as pd>>> df = pd.DataFrame({'Type':['X','X','X','Y','Y','Y'], 'value':[1,3,5,1,3,5], 'A':[3,9,4,0,2,2]})>>> df Type value A0 X 1 31 X 3 92 X 5 43 Y 1 04 Y 3 25 Y 5 2>>> df.groupby('Type')['A'].sum()TypeX 16Y 4>>> ur_dict = df.groupby('Type')['A'].sum().to_dict()>>> df['NEW'] = df['Type'].map(ur_dict)>>> df Type value A NEW0 X 1 3 161 X 3 9 162 X 5 4 163 Y 1 0 44 Y 3 2 45 Y 5 2 4希望这可以帮助。编辑以回答其他询问:您正在将元组键映射到一个系列,这会给您一个错误。在进行映射之前,您应该将需要将字典映射到的列转换为索引。见下文:>>> import pandas as pd>>> df = pd.DataFrame({'Type':['X','X','X','X','X','X','Y','Y','Y','Y','Y','Y'], 'subType':['a','a','a','b','b','b','a','a','a','b','b','b'],'value':[1,3,5,1,3,5,1,3,5,1,3,5],'A':[3,9,9,4,5,0,1,2,3,4,5,2]})>>> df Type subType value A0 X a 1 31 X a 3 92 X a 5 93 X b 1 44 X b 3 55 X b 5 06 Y a 1 17 Y a 3 28 Y a 5 39 Y b 1 410 Y b 3 511 Y b 5 2>>> df.groupby(['Type', 'subType'])['A'].sum()Type subTypeX a 21 b 9Y a 6 b 11Name: A, dtype: int64>>> ur_dict = df.groupby(['Type', 'subType'])['A'].sum().to_dict()>>> ur_dict{('X', 'a'): 21, ('X', 'b'): 9, ('Y', 'a'): 6, ('Y', 'b'): 11}>>> df['NEW'] = df.set_index(['Type', 'subType']).index.map(ur_dict)>>> df Type subType value A NEW0 X a 1 3 211 X a 3 9 212 X a 5 9 213 X b 1 4 94 X b 3 5 95 X b 5 0 96 Y a 1 1 67 Y a 3 2 68 Y a 5 3 69 Y b 1 4 1110 Y b 3 5 1111 Y b 5 2 11