![](/img/trans.png)
[英]unique combinations of values in selected columns in pandas data frame and count
[英]How to count unique combinations of values in selected columns in pandas data frame including frequencies with the value of 0?
在我的 dataframe(假設它稱為 df)中,我有兩列:一列標記為顏色,一列標記為 TOY_ID。 使用df.groupby(['Colour', 'TOY_ID']).size()
我能夠生成第三列,該列未命名,表示其他兩列的值出現在我的df。 output 示例如下所示:
Colour TOY_ID
Blue 31490.0 50
31569.0 50
50360636.0 20
..
Yellow 50360636.0 25
50366678.0 9
..
Green 31490.0 17
50366678.0 10
盡管此方法有效,但它沒有顯示前兩列值為 0 的組合。我知道這可以在 R 中完成,但我不確定如何在 Python 中做到這一點。 我想要的 output 的示例如下。 有什么建議么?
Colour TOY_ID
Blue 31490.0 50
31569.0 50
50360636.0 20
50366678.0 0
..
Yellow 31490.0 0
31569.0 0
50360636.0 25
50366678.0 9
..
Green 31490.0 17
31569.0 0
50360636.0 0
50366678.0 10
將Series.reindex
與MultiIndex.from_product
一起使用:
s = df.groupby(['Colour', 'TOY_ID']).size()
s = s.reindex(pd.MultiIndex.from_product(s.index.levels), fill_value=0)
print (s)
Colour TOY_ID
Blue 31490.0 50
31569.0 50
50360636.0 20
50366678.0 0
Green 31490.0 17
31569.0 0
50360636.0 0
50366678.0 10
Yellow 31490.0 0
31569.0 0
50360636.0 25
50366678.0 9
Name: a, dtype: int64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.