python-3.x - 计算另一列中 Id 的总行数

标签 python-3.x pandas dataframe pandas-groupby

我有一个数据框

初始化列表数据。

data = {'Id':['1', '2', '3', '4','5','6','7','8','9','10'], 'reply_id':[2, 2,2, 5,5,6,8,8,1,1]} 

创建数据框

df = pd.DataFrame(data)

   Id   reply_id
0   1   2
1   2   2
2   3   2
3   4   5
4   5   5
5   6   6
6   7   8
7   8   8
8   9   1
9   10  1

我想在 new 中为每个 Id 获取总的 reply_id

Id=1 在 reply_id 中出现了 2 次,我希望在新列 new

中出现

期望的输出

    Id  reply_id  new
0   1   2          2   
1   2   2          3     
2   3   2          0 
3   4   5          0
4   5   5          2
5   6   6          1
6   7   8          0
7   8   8          2
8   9   1          0
9   10  1          0

我已经完成了这行代码。

df['new'] = df.reply_id.eq(df.Id).astype(int).groupby(df.Id).transform('sum')

最佳答案

在这个答案中,我使用 Series.value_counts 来计算 reply_id 中的值,并将结果转换为字典。然后,我在 Id 列上使用 Series.map 将计数与 Id 相关联。 fillna(0) 用于填充 reply_id

中不存在的值
df['new'] = (df['Id']
             .astype(int)
             .map(df['reply_id'].value_counts().to_dict())
             .fillna(0)
             .astype(int))

关于python-3.x - 计算另一列中 Id 的总行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62574224/

相关文章:

r - 应用数据框列分配

python - 删除列中包含特定子字符串的行

python - 从 Pandas 输出中删除行数

python - 如何从控制台运行 twisted?

python-3.x - os.system 的多行命令

python - Pandas 合并或加入较小的数据框

python - 如何根据或/或比较合并 2 个数据帧?

python - 比较两个不同大小的数据框中的每个元素并在 Pandas 中添加或删除单词

python - 无参数输入的函数可变范围

python - 根据多个条件删除 PySpark 数据框中的行