【问题标题】:Groupby function gives me a table, not a series form?Groupby 函数给了我一个表格,而不是一个系列表格?
【发布时间】:2018-11-27 07:04:18
【问题描述】:

df:

    id  cond1   a   b   c   d
0   Q   b       1   1   nan 1
1   R   b       8   3   nan 3
2   Q   a       12  4   8   nan
3   Q   b       8   3   nan 1
4   R   b       1   2   nan 3
5   Q   a       7   9   8   nan
6   Q   b       4   4   nan 1
7   R   b       9   8   nan 3
8   Q   a       0   10  8   nan

按 id 和 cond1 分组并执行 rolling(2).sum():

df.groupby(['id','cond1']).apply(lambda x: x[x.name[1]].rolling(2).sum())

输出:

id  cond1   
Q   a      2                    nan
           5               19.00000
           8                7.00000
    b      0                    nan
           3                4.00000
           6                7.00000
R   b      1                    nan
           4                5.00000
           7               10.00000
dtype: float64

为什么是表格形式的输出?能不能是一个系列的形式和它的索引重置?

【问题讨论】:

    标签: python python-3.x dataframe pandas-groupby


    【解决方案1】:

    您可以使用reset_index() 使groupby 对象回到dataframe

    【讨论】:

    • 好的,这行得通。 df.groupby(['id','cond1']).apply(lambda x: x[x.name[1]].rolling(2).sum()).reset_index().set_index('level_2').sort_index()
    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 2021-12-18
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多