簡體   English   中英

如何計算 pandas 數據幀中選定列中值的唯一組合,包括值為 0 的頻率?

[英]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.reindexMultiIndex.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM