Pandas:分组-聚合-扩展

ux6nzvsh  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(144)

我有以下数据框

df = pd.DataFrame({"group1":["A", "A", "A","B","A","B","B","B","B","B","A","A","B"], 
                    "group2":["1", "1", "2","1","2","2","2","1","2","1","1","1","2"],
                    "date":['2022-11-01', '2022-11-01', '2022-11-02', '2022-11-01', '2022-11-01', 
'2022-11-01', '2022-11-02', '2022-11-02','2022-11-01',  '2022-11-01', '2022-11-02', '2022-11-02', '2022-11-02'], 
"value":np.random.randint(10, high=50, size=13)})

我想计算“日期”上的累积计数、累积平均值和累积方差,按“组1”和“组2”分组。
下面几行代码就能做到,但我觉得它相当笨拙。有更好的方法吗?

# sort
tmp = df.sort_values(["date", "group1", "group2"])
# cum mean
tmp2 = tmp.groupby(["group1", "group2"])["value"].expanding().mean().reset_index() 
# cum var
tmp2["var"] = tmp.groupby(["group1", "group2"])["value"].expanding().var().values
# set old index in order to get the date from original df
tmp2 = tmp2.reset_index().set_index("level_2")
tmp2 = pd.concat([tmp["date"], tmp2], axis=1).drop(['index'], axis=1) # remove "index" col
# get the cum mean and cum var for each date
tmp2 = tmp2.groupby(["group1", "group2", "date"]).agg(cnt=("value", "count"), mean=("value", "last"), var=("var", "last")).reset_index()
# create cum count column
tmp2["cumcnt"] = tmp2.groupby(["group1", "group2"])["cnt"].cumsum()
# group by
tmp2.groupby(["group1", "group2", "date"]).last()

返回以下 Dataframe

bfnvny8b

bfnvny8b1#

我使用多索引透视图,因为会有太多的NAN-hole。

import pandas as pd 
import numpy as np

df = pd.DataFrame({"group1":["A", "A", "A","B","A","B","B","B","B","B","A","A","B"], 
                    "group2":["1", "1", "2","1","2","2","2","1","2","1","1","1","2"],
                    "date":['2022-11-01', '2022-11-01', '2022-11-02', '2022-11-01', '2022-11-01', 
'2022-11-01', '2022-11-02', '2022-11-02','2022-11-01',  '2022-11-01', '2022-11-02', '2022-11-02', '2022-11-02'], 
"value":np.random.randint(10, high=50, size=13)})

g = df.groupby(['group1', 'group2', 'date'])

cumsum = pd.DataFrame( g["value"].expanding().sum().rename("cumsum") )
cummean = pd.DataFrame( g["value"].expanding().mean().rename("cummean") )
cumvar = pd.DataFrame( g["value"].expanding().var().rename("cumvar") )

r = pd.concat([cumsum, cummean, cumvar], axis=1)

r['cumcount'] = r.groupby(['group1', 'group2']).cumcount()+1

print(r)
cumsum  cummean  cumvar  cumcount
group1 group2 date                                            
A      1      2022-11-01 0     25.0     25.0     NaN         1
                         1     68.0     34.0   162.0         2
              2022-11-02 10    33.0     33.0     NaN         3
                         11    77.0     38.5    60.5         4
       2      2022-11-01 4     42.0     42.0     NaN         1
              2022-11-02 2     30.0     30.0     NaN         2
B      1      2022-11-01 3     42.0     42.0     NaN         1
                         9     63.0     31.5   220.5         2
              2022-11-02 7     42.0     42.0     NaN         3
       2      2022-11-01 5     48.0     48.0     NaN         1
                         8     85.0     42.5    60.5         2
              2022-11-02 6     41.0     41.0     NaN         3
                         12    62.0     31.0   200.0         4

相关问题