簡體   English   中英

groupby 兩列並計算第三列中的唯一值

[英]groupby two columns and count unique values from a third column

我有以下df1:

id period color size rate
1    01    red   12   30
1    02    red   12   30
2    01    blue  12   35
3    03    blue  12   35
4    01    blue  12   35
4    02    blue  12   35
5    01    pink  10   40
6    01    pink  10   40

我需要創建一個新的 df2,其索引是 3 列顏色大小比率的聚合,然后是 groupby 'period' 並獲取唯一 ID 的計數。 我的最終 df 應該具有以下結構:

index       period   count
red-12-30    01        1
red-12-30    02        1
blue-12-35   01        2
blue-12-35   03        1
blue-12-35   02        1
pink-10-40   01        2

預先感謝您的幫助。

嘗試.agg('-'.join).groupby

df1 =  df.groupby([df[["color", "size", "rate"]].astype(str)\
            .agg("-".join, 1).rename('index'), "period"])\
                .agg(count=("id", "nunique"))\
                .reset_index()
               
print(df1)

        index  period  count
0  blue-12-35       1      2
1  blue-12-35       2      1
2  blue-12-35       3      1
3  pink-10-40       1      2
4   red-12-30       1      1
5   red-12-30       2      1

你可以通過groupby來實現

 df2 = df1.groupby(['color', 'size', 'rate', 'period']).count().reset_index();
 df2['index'] = df2.apply(lambda x: '-'.join([x['color'], x['size'], x['rate']]), axis = 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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