本文介绍了 pandas 使用groupby的计数创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的df:
id item color
01 truck red
02 truck red
03 car black
04 truck blue
05 car black
我正在尝试创建一个如下所示的df:
item color count
truck red 2
truck blue 1
car black 2
我尝试过
df["count"] = df.groupby("item")["color"].transform('count')
但这不是我要寻找的. p>
任何指导表示赞赏
解决方案
这不是新列,而是新的DataFrame:
In [11]: df.groupby(["item", "color"]).count()
Out[11]:
id
item color
car black 2
truck blue 1
red 2
要获得所需的结果,请使用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
要获取新列",您可以使用transform:
In [13]: df.groupby(["item", "color"])["id"].transform("count")
Out[13]:
0 2
1 2
2 2
3 1
4 2
dtype: int64
我建议阅读文档的 split-apply-combine部分.
I have a df 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 that looks like this:
item color count
truck red 2
truck blue 1
car black 2
I have tried
df["count"] = df.groupby("item")["color"].transform('count')
But it is not quite what I am searching for.
Any guidance is appreciated
解决方案
That's not a new column, that's a new DataFrame:
In [11]: df.groupby(["item", "color"]).count()
Out[11]:
id
item color
car black 2
truck blue 1
red 2
To get the result you want is to 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 could 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
I recommend reading the split-apply-combine section of the docs.
这篇关于 pandas 使用groupby的计数创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!