在python中基于count和unique count添加列

2024-04-26 20:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的数据帧。你知道吗

type item
new apple
new apple
new io
new io
old apple
old io
old io 
old se
old pj
etc el

我需要基于count和unique count创建一个新的数据帧

type    type_count  unique_item_count
new            4    2
old            5    4
etc            1    1

列“type\u count”基于列“type”中标签的频率 列'unique\u item\u count'基于列'type'中每个唯一标签的列'item'中存在的标签的唯一计数

如果我添加一个新列

type    item    val
new apple       20
new apple       6
new io          5
new io          6
old apple       5
old io          6
old io          4
old se          5
old pj          3
etc el          2

想要一个新的数据帧

type    type_count  unique_item_count   total_count
new             4                   2   37
old             5                   4   23
etc             1                   1   2

col'total\ U count'是每种类型的col'val'中存在的金额总和


Tags: 数据ioapplenewtypecountetcval
1条回答
网友
1楼 · 发布于 2024-04-26 20:24:42

使用^{}和元组列表-第一个值指定新的列名和第二个聚合函数,这里是^{}^{}

L = [('type_count','size'), ('unique_item_count','nunique')]
df = df.groupby('type', sort=False)['item'].agg(L).reset_index()
print (df)
  type  type_count  unique_item_count
0  new           4                  2
1  old           5                  4
2  etc           1                  1

相关问题 更多 >