2015-04-24 225 views
6

創建計數新的專欄中,我有一個DF,看起來像下面這樣:大熊貓從GROUPBY

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') 

但它不是我正在尋找的。

任何指導表示讚賞

回答

17

這不是一個新列,這是一個新的數據框:

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 

要獲得一個可以使用變換的「新列」:

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 section of the docs

+0

非常感謝!以前從未見過拆分應用組合頁面。 – GNMO11