This question already has answers here:
Pandas group-by and sum
                                
                                    (7个答案)
                                
                        
                        
                            How do I create a new column from the output of pandas groupby().sum()?
                                
                                    (2个答案)
                                
                        
                                在11个月前关闭。
            
                    
我似乎找不到适用于谷歌搜索这个问题的正确措词,因为我得到的答案非常相似,但答案不正确。

我正忙于处理《泰坦尼克号》数据集,并希望对一个家庭中尚存成员的数量求和。因此,数据集如下所示:

+-------------+----------+-----------+-------------+| PassengerId | Survived | Surname | NumSurvived |+-------------+----------+-----------+-------------+| 1 | 0 | Braund | || 2 | 1 | Cumings | || 3 | 1 | Heikkinen | || 4 | 1 | Futrelle | || 5 | 0 | Braund | || 6 | 0 | Moran | || 7 | 0 | Futrelle | || 8 | 0 | Braund | || 9 | 1 | Cumings | |+-------------+----------+-----------+-------------+

我需要像这样在NumSurvived列中汇总每个姓氏的Survived值:

+-------------+----------+-----------+-------------+| PassengerId | Survived | Surname | NumSurvived |+-------------+----------+-----------+-------------+| 1 | 0 | Braund | 0 || 2 | 1 | Cumings | 2 || 3 | 1 | Heikkinen | 1 || 4 | 1 | Futrelle | 1 || 5 | 0 | Braund | 0 || 6 | 0 | Moran | 0 || 7 | 0 | Futrelle | 1 || 8 | 0 | Braund | 0 || 9 | 1 | Cumings | 2 |+-------------+----------+-----------+-------------+

最佳答案

尝试:

df['NumSurvived']=df.groupby('Surname')['Survived'].transform(lambda x: x.eq(1).sum())


打印(df)

   PassengerId  Survived    Surname  NumSurvived
0            1         0     Braund            0
1            2         1    Cumings            2
2            3         1  Heikkinen            1
3            4         1   Futrelle            1
4            5         0     Braund            0
5            6         0      Moran            0
6            7         0   Futrelle            1
7            8         0     Braund            0
8            9         1    Cumings            2

08-24 17:38