深度阅读

Pandas create new column with count from groupby

作者
作者
2023年08月22日
更新时间
9.61 分钟
阅读时间
0
阅读量

Pandas create new column that looks like the following:

id        item        color
01        truck       red
02        truck       red
03        car         black
04        truck       blue
05        car         black

I am trying to create a df.

item      color       count
truck     red          2
truck     blue         1
car       black        2

That’s not a new column, that’s a new data frame:

In [11]: df.groupby(["item", "color"]).count()
Out[11]:
             id
item  color
car   black   2
truck blue    1
      red     2

Use reset_index:

In [12]: df.groupby(["item", "color"])["id"].count().reset_index(name="count")
Out[12]:
    item  color  count
0    car  black      2
1  truck   blue      1
2  truck    red      2

To get a “new column” , you can use transform :

In [13]: df.groupby(["item", "color"])["id"].transform("count")
Out[13]:
0    2
1    2
2    2
3    1
4    2
dtype: int64

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。