簡體   English   中英

通過聚合在pandas組中包含缺少的值組合

[英]Including missing combinations of values in a pandas groupby aggregation

問題

通過聚合在pandas group的輸出中包括所有可能的值或值組合。

示例pandas DataFrame有三列, UserCodeSubtotal

import pandas as pd
example_df = pd.DataFrame([['a', 1, 1], ['a', 2, 1], ['b', 1, 1], ['b', 2, 1], ['c', 1, 1], ['c', 1, 1]], columns=['User', 'Code', 'Subtotal'])

我想對UserCode進行分組,並為每個UserCode組合獲取一個小計。

print(example_df.groupby(['User', 'Code']).Subtotal.sum().reset_index())

我得到的輸出是:

  User   Code   Subtotal
0    a      1          1
1    a      2          1
2    b      1          1
3    b      2          1
4    c      1          2

如何在表中包含缺少的組合User=='c'Code==2 ,即使它在example_df中不存在?

首選輸出

下面是首選輸出, User=='c'Code==2組合的零線。

  User   Code   Subtotal
0    a      1          1
1    a      2          1
2    b      1          1
3    b      2          1
4    c      1          2
5    c      2          0

你可以使用stack unstack

print(example_df.groupby(['User', 'Code']).Subtotal.sum()
                .unstack(fill_value=0)
                .stack()
                .reset_index(name='Subtotal'))
  User  Code  Subtotal
0    a     1         1
1    a     2         1
2    b     1         1
3    b     2         1
4    c     1         2
5    c     2         0

使用MultiIndex reindex創建from_product另一個解決方案:

df = example_df.groupby(['User', 'Code']).Subtotal.sum()
mux = pd.MultiIndex.from_product(df.index.levels, names=['User','Code'])
print (mux)
MultiIndex(levels=[['a', 'b', 'c'], [1, 2]],
           labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
           names=['User', 'Code'])

print (df.reindex(mux, fill_value=0).reset_index(name='Subtotal'))
  User  Code  Subtotal
0    a     1         1
1    a     2         1
2    b     1         1
3    b     2         1
4    c     1         2
5    c     2         0

暫無
暫無

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

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