如何通过DataFrame展平Pandas group?

时间:2017-09-11 11:55:19

标签: python pandas pandas-groupby

我有一个按日期和'结果'分组的Pandas DataFrame:

api_logs.groupby([api_logs.index.date, 'Outcome']).size()
            Outcome
2017-04-22  Success      7
2017-04-24  Failure     32
            Success     59
2017-04-25  Failure     23
            Success     91
2017-04-26  Failure      1
            Success     59
2017-04-27  Failure      3
            Success      1
2017-04-28  Failure      1
            Success      2
2017-04-29  Success      3
2017-05-03  Failure     38
2017-05-04  Failure      6
            Success    727

如何展平嵌套数据,使其结构如下?

            Failure    Success
2017-04-22                   7
2017-04-24       32         59
2017-04-25       23         91
2017-04-26        1         59
2017-04-27        3          1
2017-04-28        1          2
2017-04-29        3
2017-05-03       38
2017-05-04        6        727

我的最终目标是在图表中将失败和成功联系在一起,所以也许总会有不同的方法?

1 个答案:

答案 0 :(得分:7)

使用unstack进行重塑:

df = api_logs.groupby([api_logs.index.date, 'Outcome']).size().unstack()
print (df)
Outcome     Failure  Success
2017-04-22      NaN      7.0
2017-04-24     32.0     59.0
2017-04-25     23.0     91.0
2017-04-26      1.0     59.0
2017-04-27      3.0      1.0
2017-04-28      1.0      2.0
2017-04-29      NaN      3.0
2017-05-03     38.0      NaN
2017-05-04      6.0    727.0

也可以通过参数NaN0替换为fill_value

df = api_logs.groupby([api_logs.index.date, 'Outcome']).size().unstack(fill_value=0)

print (df)
Outcome     Failure  Success
2017-04-22        0        7
2017-04-24       32       59
2017-04-25       23       91
2017-04-26        1       59
2017-04-27        3        1
2017-04-28        1        2
2017-04-29        0        3
2017-05-03       38        0
2017-05-04        6      727