列出数据中未出现的Pandas组组合

h22fl7wq  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(221)

此问题已在此处找到答案

零值分组(5个答案)
昨天关门了。
我有一个由客户和国家/地区每月使用产品的Pandas数据框架,如下所示:

df = pd.DataFrame(
[
    ('12345', 'CH', 'A', 'Prod 1'),
    ('12345', 'CH', 'A', 'Prod 2'),
    ('67890', 'DE', 'A', 'Prod 1'),
    ('98765', 'CH', 'B', 'Prod 3'),
    ('nnnnn', 'NL', 'C', 'Prod 1')
],
    columns=['Client_ID', 'Country', 'Customer', 'Product Used']
)

我想列出按客户和国家分组的产品使用总量。pandas groupby功能让我更接近我需要的东西。

df.groupby(['Customer', 'Country','Product Used']).count()

# Reuse Client_ID as Count

Customer    Country Product Used    Client_ID
A           CH      Prod 1          3
                    Prod 2          5
            DE      Prod 1          1
B           CH      Prod 3          2
C           NL      Prod 1          1

是否有办法将数据中未显示为0的组合包括在内?因此,我的结果如下所示:

Customer    Country Prod 1  Prod 2  Prod 3
A           CH      3       5       0
            DE      1       0       0
B           CH      0       0       2
C           NL      1       0       0
xfyts7mz

xfyts7mz1#

使用 pd.crosstab :

new_df = pd.crosstab([df['Customer'], df['Country']], df['Product Used'])
``` `new_df` :

Product Used Prod 1 Prod 2 Prod 3
Customer Country
A CH 1 1 0
DE 1 0 0
B CH 0 0 1
C NL 1 0 0

或 `unstack` 之后 `groupby count` 具有 `fill_value=0` 然后 `droplevel` 0来自以下列:

new_df = (
df.groupby(['Customer', 'Country', 'Product Used']).count()
.unstack(fill_value=0)
.droplevel(0, axis=1)
)
``` new_df :

Product Used      Prod 1  Prod 2  Prod 3
Customer Country                        
A        CH            1       1       0
         DE            1       0       0
B        CH            0       0       1
C        NL            1       0       0

或与 pivot_table 具有 aggfunc 数到 fill_value=0 :

new_df = (
    df.pivot_table(index=['Customer', 'Country'], columns='Product Used',
                   values='Client_ID', aggfunc='count', fill_value=0)
)
``` `new_df` :

Product Used Prod 1 Prod 2 Prod 3
Customer Country
A CH 1 1 0
DE 1 0 0
B CH 0 0 1
C NL 1 0 0

相关问题