如何向数据透视表分组添加过滤器?

问题描述 投票:0回答:1

跟进:如何根据单独的类别类型对列求和并保留零?

我使用“Id”来代替一堆列。其中之一是“日期”。我们只想考虑某个日期之后的条目。因此,您会遇到这样一种情况:ID 为 1 的某人有 10 个小时,但所有这些时间都在该目标日期之前。因此,您想要显示对于 Id_1,计数为 0。如何将此过滤器添加到数据透视表?

我认为在不应用数据透视表的情况下对数据帧进行切片是行不通的,因为我不会得到“0”填充效果。

python pandas dataframe pivot-table
1个回答
0
投票

为了清楚起见,您应该提供一个可重现的示例。

假设这个,我们要考虑

2023-01-15
之后的日期(ID 3中不存在):

   Id        Date Category  Hours
0   1  2023-01-01        A      1   # this should be filtered out
1   1  2023-02-01        A      3
2   1  2023-02-01        B      4
3   2  2023-03-01        A      2
4   2  2023-03-01        B      6
5   3  2023-01-01        A      3   # this should be filtered out

您可以预先过滤行(例如使用

query
),然后在旋转后添加缺失的 Id
reindex

out = (df.query('Date > "2023-01-15"')
         .pivot_table(index='Id', columns='Category', values='Hours',
                      aggfunc='sum', fill_value=0,
                      margins=True, margins_name='Total')
         .add_suffix('_Hours')
         .drop('Total')
         .reindex(df['Id'].unique(), fill_value=0)
         .reset_index().rename_axis(columns=None)
      )

输出:

   Id  A_Hours  B_Hours  Total_Hours
0   1        3        4            7
1   2        2        6            8
2   3        0        0            0
© www.soinside.com 2019 - 2024. All rights reserved.