Pandas:执行多个复杂聚合的惯用方法?
Pandas: idiomatic way to perform multiple complex aggregations?
我有一个table如下:
ID SCORE
A NaN
A NaN
B 1
B 2
C 5
我想要以下输出:
ID SUM_SCORE SIZE_SCORE
A NaN 2
B 3 2
C 5 1
因为我想保留 NaN,所以我需要使用 sum(min_count=1)
。所以到目前为止我有以下内容:
grp = df.groupby('ID')
sum_score = grp['SCORE'].sum(min_count=1).reset_index()
size_score = grp['SCORE'].size().reset_index()
result = pd.merge(sum_score, size_score, on=['ID'])
这感觉真的很不雅观。有没有更好的方法来获得我想要的结果?
s=df.groupby('ID').SCORE.agg([('sum_score',lambda x : x.sum(min_count=1)),
('size_score','size')] ).reset_index()
ID sum_score size_score
0 A NaN 2
1 B 3.0 2
2 C 5.0 1
您可以使用以下方式进行汇总:
df_agg = df.groupby("ID", as_index=False).agg(["sum","count"])
# rename your columns
df_agg.columns = ["ID","SUM_SCORE", "SIZE_SCORE"]
我有一个table如下:
ID SCORE
A NaN
A NaN
B 1
B 2
C 5
我想要以下输出:
ID SUM_SCORE SIZE_SCORE
A NaN 2
B 3 2
C 5 1
因为我想保留 NaN,所以我需要使用 sum(min_count=1)
。所以到目前为止我有以下内容:
grp = df.groupby('ID')
sum_score = grp['SCORE'].sum(min_count=1).reset_index()
size_score = grp['SCORE'].size().reset_index()
result = pd.merge(sum_score, size_score, on=['ID'])
这感觉真的很不雅观。有没有更好的方法来获得我想要的结果?
s=df.groupby('ID').SCORE.agg([('sum_score',lambda x : x.sum(min_count=1)),
('size_score','size')] ).reset_index()
ID sum_score size_score
0 A NaN 2
1 B 3.0 2
2 C 5.0 1
您可以使用以下方式进行汇总:
df_agg = df.groupby("ID", as_index=False).agg(["sum","count"])
# rename your columns
df_agg.columns = ["ID","SUM_SCORE", "SIZE_SCORE"]