python - 如何分组并计算该组 Pandas 中的总数
问题描述
您好我有以下数据框:
# Import pandas library
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
# initialize list of lists
data = [['tom', 10,1], ['nick', 15,0], ['tom', 14,1], ['jason', 15,0], ['nick', 18,1], ['jason', 15,0], ['jason', 17,1]
, ['tom', 14,0], ['nick',16 ,1], ['tom', 22,1]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Target'])
# print dataframe.
df
Name Attempts Target
0 tom 10 1
1 nick 15 0
2 tom 14 1
3 jason 15 0
4 nick 18 1
5 jason 15 0
6 jason 17 1
7 tom 14 0
8 nick 16 1
9 tom 22 1
我希望简单地在每个名字旁边得到一个总数,这样它就变成了:
Name Attempts Target totalentries
0 tom 10 1 4
1 nick 15 0 3
2 tom 14 1 4
3 jason 15 0 3
4 nick 18 1 3
5 jason 15 0 3
6 jason 17 1 3
7 tom 14 0 4
8 nick 16 1 3
9 tom 22 1 4
试过:
df['totalentries'] = df.groupby('Name').nunique()
但得到一个ValueError: Wrong number of items passed 8, placement implies 1
有任何想法吗?非常感谢!
解决方案
与聚合函数GroupBy.transform
后的指定列一起使用:groupby
df['totalentries'] = df.groupby('Name')['Target'].transform('nunique')
如果需要计算值:
df['totalentries'] = df.groupby('Name')['Target'].transform('size')
推荐阅读
- python - “import json”在 IDLE 中运行良好,但在 Windows 7 cmd 中失败
- php - Wordpress 循环浏览帖子
- algorithm - 3D 中的整流罩数据点
- android - 模拟器:模拟器:错误:使用相同的 AVD 运行多个模拟器是一项实验性功能
- node.js - 在 MarkoJs “入门”教程中遇到错误
- reactjs - 一个节点不能在状态树中存在两次( mobx-state-tree )
- parse-platform - 解析服务器 - 如何从云代码中的 ParseGeoPoint 中提取经度+纬度
- spring-boot - Spring Boot - 无法配置 CORS 选项策略
- unit-testing - 在 UWP/WinIot 核心中找不到 ViewModelLocator
- python - xpath 刮出来的空白,是什么问题?