熊猫分组并将行转换为列

Lil*_*lly 1 python dataframe pandas pandas-groupby

我有如下销售数据集:df1

district      item       Year    salesAmount
Arba          pen        2019    10
Arba          pen        2019    20
Arba          pencil     2018    30
Arba          pencil     2018    30
Arba          pencil     2019    30
Cebu          pen        2019    100
Cebu          pen        2019    300
Cebu          pen        2018    100
Cebu          pen        2018    100
Cebu          pen        2019    100
Cebu          laptop     2019    20000
Cebu          laptop     2018    20000
Cebu          fruit      2019    200
Cebu          fruit      2018    800
Cebu          fruit      2019    800
Cebu          fruit      2018    100
Run Code Online (Sandbox Code Playgroud)

我可以完成 groupby 并分别获得 2018 年和 2019 年每个产品的总和。

result = df1.groupby(['district', 'item', 'Year'], as_index=False)['salesAmount'].sum()
Run Code Online (Sandbox Code Playgroud)

但我想有一个表格列如下 inroder 做进一步的列转换

预期输出:

district      item       2018_sales    2019_sales
Arba          pen        0             30
Arba          pencil     60            30
Cebu          pen        500           200
Cebu          laptop     20000         20000
Cebu          fuit       900           1000
Run Code Online (Sandbox Code Playgroud)

谢谢。

Ale*_*der 6

鉴于您之前的 计算result,只需使用数据透视表和一些额外的格式化步骤来扩展它。请注意,默认aggfunc为pivot_table是'mean',但考虑到这些值已在上一步中聚集也不会,如果你喜欢使用有所作为np.sum。

result = (
    result
    .pivot_table(index=['district', 'item'], columns=['Year'], values='salesAmount', fill_value=0)
    .add_suffix('_sales')
    .reset_index()
)
result.columns.name = None
>>> result
  district    item  2018_sales  2019_sales
0     Arba     pen         0.0        30.0
1     Arba  pencil        60.0        30.0
2     Cebu   fruit       900.0      1000.0
3     Cebu  laptop     20000.0     20000.0
4     Cebu     pen       200.0       500.0
Run Code Online (Sandbox Code Playgroud)

当然,你也可以忘记首字母groupby,直接做pivot_table:

result = (
    df1
    .pivot_table(
        index=['district', 'item'], 
        columns=['Year'], 
        values='salesAmount', 
        fill_value=0,
        aggfunc='sum'
    )
    .add_suffix('_sales')
    .reset_index()
)
Run Code Online (Sandbox Code Playgroud)